我想在表格中添加一列并返回总和。我有一个循环,但是没有用。
while ($row = mysql_fetch_assoc($result)){ $sum += $row['Value']; } echo $sum;
您可以在MySQL查询中完全处理它:
SELECT SUM(column_name) FROM table_name;
在PHP代码中,尝试以下操作:
$result = mysql_query('SELECT SUM(value) AS value_sum FROM codes'); $row = mysql_fetch_assoc($result); $sum = $row['value_sum'];
使用PDO(mysql_query已弃用)
mysql_query
$stmt = $handler->prepare("SELECT SUM(value) AS value_sum FROM codes"); $stmt->execute(); $row = $stmt->fetchAll(PDO::FETCH_OBJ); $sum = $row->value_sum;