doupao6698 2016-11-22 13:09
浏览 28
已采纳

在php中添加所有行值

This is the table

store_reviews

id   rev_star
1       2
2       5
3       4

What I want to do is to get all the rows and add stars and divide by the count of rows (average) like 2+5+4/3

I wrote a code but it doesn't get all the rows added.

<?php
          $stmtrev = $mysqli->prepare("SELECT * FROM store_reviews WHERE store_id=?");
          $stmtrev->bind_param("i", $_GET['storeid']);
          $stmtrev->execute();
          $revrows = $stmtrev->get_result();
          $stmtrev->close();
          $total=0;
          while ($stars = $revrows->fetch_assoc()) 
          {
            $count = ($total + $stars['rev_star']);
          }
           $count/count($revrows->fetch_assoc());
        ?>

Can anyone explain what's wrong and what could be done?

  • 写回答

1条回答 默认 最新

  • douxie0824 2016-11-22 13:25
    关注

    This is one of those places where your database can do the work for you

    SELECT AVG(rev_star) as average, 
    FROM store_reviews 
    WHERE store_id=?
    

    As to why your PHP script isn't working properly, you're counting the number of columns in your database, not the number of rows. Worse, you're doing this by trying to pop a result set off the result stack after having looped through the full result stack. The result object tells you how many rows were returned

    $total = 0;
    while ($stars = $revrows->fetch_assoc()) $total += $stars['rev_star'];
    $avg = $total / $revrows->num_rows;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大