Get sum of MySQL column in PHP

ghz 1years ago ⋅ 7589 views

Question

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;

Answer

You can completely handle it in the MySQL query:

SELECT SUM(column_name) FROM table_name;

Using PDO (mysql_query is deprecated)

$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];

Or using mysqli:

$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes'); 
$row = mysqli_fetch_assoc($result); 
$sum = $row['value_sum'];