获取PHP中MySQL列的总和 [英] Get sum of MySQL column in PHP
本文介绍了获取PHP中MySQL列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要在表格中添加一列并返回总和.我有一个循环,但是没有用.
I have a column in a table that I would like to add up and return the sum. I have a loop, but it's not working.
while ($row = mysql_fetch_assoc($result)){
$sum += $row['Value'];
}
echo $sum;
推荐答案
您可以在MySQL查询中完全处理它:
You can completely handle it in the MySQL query:
SELECT SUM(column_name) FROM table_name;
在PHP代码中,尝试以下操作:
In the PHP code, try this:
$result = mysql_query('SELECT SUM(value) AS value_sum FROM codes');
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
使用PDO(不推荐使用mysql_query
)
Using PDO (mysql_query
is deprecated)
$stmt = $handler->prepare("SELECT SUM(value) AS value_sum FROM codes");
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_OBJ);
$sum = $row->value_sum;
这篇关于获取PHP中MySQL列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文