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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法