php - 计算while循环中的总num行数

时间:2013-09-26 12:18:17

标签: php 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')

如何计算总数?

(P.S。$ i必须设为0)

4 个答案:

答案 0 :(得分:13)

简单:

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

echo $counter;

在循环外定义变量。

答案 1 :(得分:0)

我没有得到你的问题......但我认为你想要计算总更新行

 $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

答案 2 :(得分:0)

你应该在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;

答案 3 :(得分:0)

这是您的原始查询:

          $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