通常要检查从数据库中获取的记录数,我们rowCount在使用 PDO 和 PHP 时使用函数。但是,我遇到了一种情况,我想在if...else语句中使用相同的结果,但我不能使用它,我将在下面用代码示例解释原因。
正常情况:
$stmt = $pdo->prepare("SELECT * FROM table");
$stmt-> execute();
$count = $stmt->rowCount();
if($count > 0){
while($row = $stmt->fetch()){
// Perform a task....
}
}
或者,我们也使用SELECT COUNT(*) as cnt FROM table然后使用 fetch 作为 count 元素。
但是,我的问题是我不能使用这些方法,因为它们将返回已执行的根查询的计数值。在这里,我有一个if条件,当满足时加载结果,我想计算满足该条件的记录总数。
例如:
$stmt = $pdo->prepare("SELECT * FROM table");
$stmt-> execute();
while($row = $stmt->fetch()){
// Suppose I have a variable $distance which I calculated and based on that the result should appear
if($distance < 100){
// Display the records which satisfied this condition
// Once the records are fetched, NOW I WANT TO COUNT THEM under "this" condition.
// This count will be based on the condition above which will be different from the root count using `rowCount`
if($count == 0){
// Perform a task here
}
}
}
如何计算条件下满足的记录数if($distance < 100)?任何帮助,将不胜感激。
紫衣仙女