doufu6504 2016-04-14 08:54
浏览 128
已采纳

来自MySQL表的PHP PDO计数和总和值

Well, I'm pretty sure this is just a novice question, so please forgive me for that, but I feel like I'm losing my mind.

I have a simple MySQL rating table and I need to count rows and to sum rates values (int) with PHP PDO

$sql = "SELECT rate FROM rating_table";
$query = $db->query($sql);            

$rate_times = count($query->fetchAll()); // it works! 
echo '<p>'.$rate_times.'</p>';

$sum_rates = array_sum($query->fetchAll()); // it doesn't work!
echo '<p>'.$sum_rates.'</p>';

Thank you in advance for any suggestion

  • 写回答

1条回答 默认 最新

  • dsfds2343 2016-04-14 08:57
    关注

    If I understand you right, all you have to do is to modify your sql request, this will return a single row

    sql = "SELECT sum(rate) as rate_sum, count(*) as record_count FROM rating_table";
    $query = $db->query($sql);            
    $row = $query->fetch(PDO::FETCH_ASSOC);
    if ($row) {
      $sum = $row['rate_sum'];
      $count = $row['record_count'];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥50 用logisim设计16位单时钟周期cpu
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据
  • ¥15 请上面代码做什么处理或什么混淆
  • ¥15 英雄联盟自定义房间置顶
  • ¥15 W5500网线插上无反应
  • ¥15 如何用字典的Key,显示在WPF的xaml中
  • ¥15 weautomate读取Excel表格信息然后填写到网页一直报错,如何解决?
  • ¥15 C#如何在Webview2中获取网页验证码