[英]Count total sum of rows in while loop
好吧,我有這樣的查詢
$get_downlines = "SELECT * FROM referrals WHERE ref_upline = :rupline";
$get_downlines = $pdo->prepare($get_downlines);
$get_downlines-> bindValue(':rupline', $sessionid);
$get_downlines-> execute();
while($fetch_downlines = $get_downlines->fetch()){
$rdownline = $fetch_downlines['ref_downline'];
$dr = "SELECT * FROM `ads_viewed` WHERE av_user = :user";
$dr = $pdo->prepare($dr);
$dr-> bindValue(':user', $rdownline);
$dr-> execute();
echo $dr_count = $dr->rowCount();
}
上面的代碼為我提供了3456
行計數(所有都是單獨的計數,例如3、4、5、6)。 現在,我想在這里總結所有這些行,並得到結果為3+4+5+6 = 18
。 並將其分配給一個全局變量,該變量可以在while循環之外的任何地方使用(如果可能)。 如何才能做到這一點?
您可以執行以下操作:
$get_downlines = "SELECT * FROM referrals WHERE ref_upline = :rupline";
$get_downlines = $pdo->prepare($get_downlines);
$get_downlines-> bindValue(':rupline', $sessionid);
$get_downlines-> bindValue(':direct', "direct");
$get_downlines-> execute();
$totalrows;
while($fetch_downlines = $get_downlines->fetch()){
$rdownline = $fetch_downlines['ref_downline'];
$dr = "SELECT * FROM `ads_viewed` WHERE av_user = :user";
$dr = $pdo->prepare($dr);
$dr-> bindValue(':user', $rdownline);
$dr-> execute();
echo $dr_count = $dr->rowCount();
$totalrows+= $dr->rowCount();
}
echo $totalrows;
首先,您創建$totalrows;
循環外的變量。 您可以使用$totalrows += $dr->rowCount();
在查詢中$totalrows += $dr->rowCount();
行數來增加此變量$totalrows += $dr->rowCount();
在while循環內
這可以通過一個查詢來完成:
$stmt = $pdo->prepare("
SELECT COUNT(*) AS cnt
FROM referrals
JOIN ads_viewed ON ads_viewed.av_user = referrals.ref_downline
WHERE ref_upline = :rupline
");
$stmt->execute(['rupline' => $sessionid]);
$dr_count = $stmt->fetchColumn();
注意:每次在while-fetch-loop中執行SQL查詢時,最好使用JOIN。 每次使用SELECT *
只是為了獲取行數時,您就在浪費資源,應該使用COUNT(*)
代替。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.