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;
解决方案
You can completely handle it in the MySQL query:
SELECT SUM(column_name) FROM table_name;
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'];
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;