繁体   English   中英

PHP-计算while循环内的总行数

[英]php - count total num rows inside while loop

我有这段代码:

  $i=0;
      $start_date = date("Y/m/d");
      $end_date = date('Y/m/d', strtotime($start_date . " -7 days"));



      while($days7=mysql_fetch_assoc($q)): 
          $next_date = strtotime($i--." days", strtotime($start_date));
          $date = date("Y/m/d",$next_date); 
      #Let's get the latest click combined from the latest 7 days
          $combined7=mysql_query("SELECT sum(value) FROM `xeon_stats_clicks` WHERE user='".$userdata['username']."' AND typ='4' AND data='$date' ORDER BY data DESC LIMIT 8") or die(mysql_error());              


      print mysql_num_rows($combined7);

      endwhile;  

我需要查看$combined7正在获得多少行。 目前,我正在使用print mysql_num_rows($combined7); 但这只是打印出来:1 1 1 1 1(每行数字“ 1”)

如何计算总数?

(PS $ i必须设置为0)

简单:

$counter = 0;
while(..) {
      $counter++; // or $counter = $counter + 1;
}

echo $counter;

在循环外定义变量。

我没有正确回答您的问题..但是我认为您想统计更新的总行数

 $sum=0;
 while(){
 $sum += mysql_num_rows($combined7); //here it will add total upadted row in $sum...
 print $sum; // if you want to print every time total
 }
 print $sum; // if you want to print only one time total

您应该在while之前定义一个值为0的变量。 那么您可以在while内递增此变量的值。 然后在一段时间结束后打印此变量。

      $start_date = date("Y/m/d");
      $end_date = date('Y/m/d', strtotime($start_date . " -7 days"));
      $sn = 0;
      while($days7=mysql_fetch_assoc($q)): 
          $next_date = strtotime($i--." days", strtotime($start_date));
          $date = date("Y/m/d",$next_date); 
      #Let's get the latest click combined from the latest 7 days
          $combined7=mysql_query("SELECT sum(value) FROM `xeon_stats_clicks` WHERE user='".$userdata['username']."' AND typ='4' AND data='$date' ORDER BY data DESC LIMIT 8") or die(mysql_error());              


      $sn += mysql_num_rows($combined7);

      endwhile;
      print $sn;

这是您的原始查询:

          $combined7=mysql_query("SELECT sum(value) FROM `xeon_stats_clicks` WHERE user='".$userdata['username']."' AND typ='4' AND data='$date' ORDER BY data DESC LIMIT 8")

通过添加COUNT命令,它将计算SUM中考虑的行数:

SELECT SUM(value), COUNT(value) FROM...

然后,当您取回MYSQL_RESULT ,需要获取数据:

$data = mysql_fetch_array($combined7);

然后将具有以下数组:

Array(
    [0] = SUM
    [1] = COUNT
)

注意: mysql_*已被弃用。 请改用mysqli_*或PDO

暂无
暂无

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

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