通常要檢查從數據庫中獲取的記錄數,我們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)?任何幫助,將不勝感激。
1 回答
紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
$count = 0;
while($row = $stmt->fetch()){
if($distance < 100){
$count++;
// display records
}
}
if($count == 0){
// Perform a task here
}
您可以使用 while 循環計算記錄,如上所示。我假設你已經完成bind_result了$display. 在循環之外,如果您找到count = 0,則執行您想要的任務。
- 1 回答
- 0 關注
- 150 瀏覽
添加回答
舉報
0/150
提交
取消
