【问题标题】:Fetching number of rows after PDO executePDO 执行后获取行数
【发布时间】:2025-12-13 13:15:01
【问题描述】:

我正在尝试显示搜索后在数据库中找到的行数。

这是我的代码:

$city =  $_POST['city'];
 $bloodType = $_POST['donorType'];

     $q = $db->prepare("SELECT count(*) FROM  `users` AS numusers WHERE `city` = :city  AND `bloodType` = :bloodType");
     $q->bindValue(":city",$city,PDO::PARAM_INT);
     $q->bindValue(":bloodType",$bloodType);
     $q->execute();

    while($row = $q->fetch(PDO::FETCH_ASSOC)){
    echo "<p align='center'><h5> There is/are <span class='red-text'>".$row['numusers']."</span> available donor(s) found.
    You must be a <b><a href='register.php'>registered user</a></b> to view their details.</h5></p>";
      }

这是我最后一次尝试。我收到此错误消息 `注意:未定义的索引:numusers

我该如何解决这个提示?

【问题讨论】:

  • 应该是这样 SELECT count(*) as numusers

标签: php sql pdo


【解决方案1】:

只需创建count(*)的别名

SELECT count(*) AS numusers..

应该是

$q = $db->prepare("SELECT count(*) AS  numusers FROM `users` WHERE `city` = :city  AND `bloodType` = :bloodType");

【讨论】:

  • You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AS numusers` users WHERE city = '3' AND bloodType = '4''` 我收到此错误消息
  • numusers中删除反引号,只需使用SELECT count(*) AS numusers..
  • 在更新的问题中,您创建表的别名,您需要创建 count(*) 的别名检查更新的答案!
  • 谢谢!我将AS numusers 放在FROM users 之后`` 我不知道它不会那么敏感哈哈。谢谢,上帝保佑:)
  • 将在 5 分钟后勾选检查 :)
【解决方案2】:

在 PDO 中有一个特殊的方法来检索这种数据 - 查询返回的单个值,PDOStatement::fetchColumn()。因此,您根本不必为别名而烦恼。

此外,这里的while循环是多余的。

$city =  $_POST['city'];
$bloodType = $_POST['donorType'];

$q = $db->prepare("SELECT count(*) FROM  `users` WHERE `city` = :city  AND `bloodType` = :bloodType");
$q->bindValue(":city", $city, PDO::PARAM_INT);
$q->bindValue(":bloodType", $bloodType);
$q->execute();
$numusers = $q->fetchColumn();

echo "<p align='center'><h5> There is/are <span class='red-text'>$numusers</span> available donor(s) found.
You must be a <b><a href='register.php'>registered user</a></b> to view their details.</h5></p>";

【讨论】:

    最近更新 更多