3

我有这段代码:

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

4

4 回答 4

21

简单的:

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

echo $counter;

在循环外定义变量。

于 2013-09-26T12:21:29.393 回答
1

这是您的原始查询:

          $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

于 2013-09-26T12:40:14.527 回答
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
于 2013-09-26T12:21:41.617 回答
0

您应该在 while 之前定义一个值为 0 的变量。然后你在while内增加这个变量的值。然后在 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;
于 2013-09-26T12:23:17.527 回答