简体   繁体   中英

Count total sum of rows in while loop

Okay so I have a query like this one

$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();
}

The code above gives me the row counts as say 3456 (all are separate counts like 3,4,5,6). Now I want to sum up all these rows here and get the result as 3+4+5+6 = 18 . And assign it to a global variable which can be used anywhere outside while loop (if possible). How can this be done?

You could do the following:

$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;

First you create the $totalrows; variable outside of the loop. You can increment this variable with the amount of rows in your query using $totalrows += $dr->rowCount(); inside of the while loop

This can be done with a single query:

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

Note: Everytime you execute an SQL query in a while-fetch-loop you probably better use a JOIN. And everytime you use SELECT * just to get the number of rows, you are wasting resources and should use COUNT(*) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM