计算while循环中的总行数

时间:2017-03-10 17:30:04

标签: php html mysql html5 pdo

好的,我有一个像这样的查询

$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的结果。并将其分配给一个全局变量,该变量可以在循环外的任何地方使用(如果可能)。怎么办呢?

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

$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;变量。您可以使用while循环中的$totalrows += $dr->rowCount();

,使用查询中的行数增加此变量

答案 1 :(得分:1)

这可以通过一个查询来完成:

$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(*)