doude2635 2019-03-28 19:49
浏览 62
已采纳

帮助SQL SUM()?

I am not sure if I am supposed to use SUM() for this, but I wanted to get the sum of all the values in the "earnedcoins" column and this is my code:

$sql = "SELECT SUM(earnedcoins) FROM users";
$result = mysqli_query($conn, $sql);
$earnedcoins = mysqli_num_rows($result); 
echo $earnedcoins;
$conn->close();

Unfortunately, it just stamps out number 1. Can anybody help me resolve this issue? Any help will be appreciated.

  • 写回答

1条回答 默认 最新

  • duanliang789262 2019-03-28 19:52
    关注

    mysqli_num_rows() will always return 1 for that query, as you only get one row returned - which is the number of summed rows. Instead, you need to fetch that value from SUM().

    Give the SUM() an alias, and fetch the value. You should also use GROUP BY when using aggregate functions like SUM() - I don't know your table-structure, but perhaps GROUP BY id if that exists.

    $sql = "SELECT SUM(earnedcoins) as result FROM users";
    $result = mysqli_query($conn, $sql);
    $sum = $result->fetch_assoc()['result'];
    echo $sum;
    $conn->close();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集