php - Telegram Bot 和 Mysqli_fetch_assoc 问题
问题描述
我正在用 PHP 制作一个 Telegram 机器人。我已经连接了一个 Mysql 数据库,我需要在一条独特的消息中打印一些结果。但是当我启动命令时,它会打印出一些消息。如何在唯一的消息中打印所有结果?
这是代码:
if($data == 'rawliberi'){
$thequery = "SELECT * FROM uwgliberi WHERE roster='OCW'";
$thequeryup = mysqli_query($conn, $thequery);
while($row = mysqli_fetch_assoc($thequeryup)){
$Alex -> Request('sendMessage', ['chat_id' => $chat_id, 'text' => $row['wrestlername'], 'parse_mode' => 'HTML']);
}
}
解决方案
您正在为查询中的每个结果发送一条消息,因为对所有行都执行了 while 循环。如果我理解正确,您想发送一条包含所有查询结果的消息。我建议您使用PDO从/向数据库连接和获取/插入数据,因为它更安全。
试试这个:
<?php
$pdo = new PDO("mysql:host=localhost;dbname=DATABASE_NAME", "USERNAME", "PASSWORD");
if($data == 'rawliberi'){
$allResults = "";
$stmt = $pdo->prepare("SELECT * FROM uwgliberi WHERE roster=:roster"); // Prepare the query
$stmt->execute(['roster' => "OCW"]); // Replace parameters starting with ":" with the given value (e.g. replace ":roster" with "OCW") and execute the query
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC); // Insert results in the $results variable
/*
Result's value example
[
{
"id": "1",
"wrestlername": "Nicola",
"roster": "OCW"
},
{
"id": "2",
"wrestlername": "Mauro",
"roster": "OCW"
},
{
"id": "3",
"wrestlername": "Don Gino",
"roster": "OCW"
}
]
*/
for ($i = 0; $i < count($results); $i++){ // Execute this loop for each result in $results. The count() function return the count of the results
$allResults .= $results[$i]['wrestlername'] . "\n"; // Add the wrestlername to the allResults variable and go to a new line (\n) so the names won't be "NicolaMauroDon Gino"
}
$Alex->Request('sendMessage', ['chat_id' => $chat_id, 'text' => $allResults, 'parse_mode' => 'HTML']);
}
推荐阅读
- c# - 如何修复 EF Core 中的“远程主机强制关闭现有连接”错误
- django - 如何在 django 应用程序启动时安装 sql 函数
- spring-boot - 如何在 Spring Boot WebSocket 中使用自动装配组件?
- php - 我的语法关闭了,我不太明白,PHP 和 HTML,简单的 echo 语句
- javascript - Hooks 只能在函数组件的主体内部调用。但它已经在一个函数中
- recursion - 如何使用elixir递归实现二叉搜索树的高度?
- html - 如何使用服务器端渲染将我的反应服务器与 django 服务器结合起来?
- apache-nifi - 脚本在终端中运行良好,但在使用 ExecuteStreamCommand 运行时“未找到”
- python - 流式传输到网站而不是 Window OpenCV
- python - 使用Tkinter时如何解决Base64图像错误