PHP MYSQL PDO列的总和 [英] PHP MYSQL PDO SUM of columns

查看:80
本文介绍了PHP MYSQL PDO列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是php的新手,我已经搜索了过去一个小时,并阅读了所有可以找到的文档,但没有任何帮助.我有一个表,其中有一堆数据行.我正在尝试从整个表格中选择一列,并将它们全部加在一起.这就是我得到的.这一切告诉我,有多少行与我的查询匹配,而不是我想要的列的总和.感谢您的帮助.

I'm new to php and I've searched for the past hour and read all the documentation I could find and nothing is helping. I have a table that has a bunch of rows of data. I'm trying to pick one column from the whole table and add them all together. Here is what I got. All this tells me is how many rows there are that match my query, not the total sum of column I want. Any help is appreciated.

$res1 = $db->prepare('SELECT sum(distance) FROM trip_logs WHERE user_id = '. $user_id .' AND status = "2"');
$res1->execute();
$sum_miles = 0;
while($row1 = $res1->fetch(PDO::FETCH_ASSOC)) {
$sum_miles += $row1['distance'];
}
echo $sum_miles;

推荐答案

在这种情况下,您只返回一行.修改汇总列以使用别名:

You're only returning one row in this instance. Modify your summed column to have an alias:

SELECT SUM(distance) AS totDistance FROM trip_logs ....

现在您可以提取行-

$row = $res1->fetch(PDO::FETCH_ASSOC);
echo $row['totDistance'];

无需循环.

这篇关于PHP MYSQL PDO列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆