简体   繁体   English

计算while循环中的总行数

[英]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). 上面的代码为我提供了3456行计数(所有都是单独的计数,例如3、4、5、6)。 Now I want to sum up all these rows here and get the result as 3+4+5+6 = 18 . 现在,我想在这里总结所有这些行,并得到结果为3+4+5+6 = 18 And assign it to a global variable which can be used anywhere outside while loop (if possible). 并将其分配给一个全局变量,该变量可以在while循环之外的任何地方使用(如果可能)。 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; 首先,您创建$totalrows; variable outside of the loop. 循环外的变量。 You can increment this variable with the amount of rows in your query using $totalrows += $dr->rowCount(); 您可以使用$totalrows += $dr->rowCount();在查询中$totalrows += $dr->rowCount();行数来增加此变量$totalrows += $dr->rowCount(); inside of the while loop 在while循环内

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. 注意:每次在while-fetch-loop中执行SQL查询时,最好使用JOIN。 And everytime you use SELECT * just to get the number of rows, you are wasting resources and should use COUNT(*) instead. 每次使用SELECT *只是为了获取行数时,您就在浪费资源,应该使用COUNT(*)代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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