dpmkif3097 2018-02-25 16:41
浏览 66
已采纳

在PHP中按ID显示总和[重复]

I have a table table_log filled with logs with different IDs but some of those logs have the same ID. I have to get the sum of column counter of those with the same ID id then display the results a column total_count. This is my query:

SELECT id, SUM(counter) AS total_count FROM table_log GROUP BY id

I have to display this in a table column using PHP. This is what I have:

  1. $sql = "SELECT id, SUM(counter) AS total_count FROM table_log GROUP BY id";
  2. $row = mysql_fetch_assoc($sql);
  3. $sum = $row['total_count'];
  4. $data .= "<td style='width: 200px;' align=center >". $sum ."</td>";

It's not appearing in the table. What should I input instead?

EDIT : I didn't choose to use this. The company did.

</div>
  • 写回答

1条回答 默认 最新

  • dps69208 2018-02-25 16:44
    关注

    Firstly - mysql_* functions are deprecated. Avoid them as much as possible.

    Secondly, you need to run the query first, before you can fetch the results.

    1. $conn = mysqli_connect("localhost", "root", "", "db"); //connection string
    2. $q = mysqli_query($conn, $sql);
    3. $row = mysqli_fetch_assoc($q);

    Then it'll work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部