我试图在搜索后显示数据库中找到的行数。
这是我的代码:
$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
如何解决这些提示?
答案 0 :(得分:2)
只需创建count(*)
SELECT count(*) AS numusers..
这将是
$q = $db->prepare("SELECT count(*) AS numusers FROM `users` WHERE `city` = :city AND `bloodType` = :bloodType");
答案 1 :(得分:1)
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>";