[php] Get sum of MySQL column in PHP

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;

This question is related to php mysql

The answer is


Get Sum Of particular row value using PHP MYSQL

"SELECT SUM(filed_name) from table_name"

$sql = "SELECT SUM(Value) FROM Codes";

$result = mysql_query($query);

while($row = mysql_fetch_array($result)){

    sum = $row['SUM(price)'];

}

echo sum;

$row['Value'] is probably a string. Try using intval($row['Value']).

Also, make sure you set $sum = 0 before the loop.

Or, better yet, add SUM(Value) AS Val_Sum to your SQL query.


Try this:

$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];

Let us use the following image as an example for the data in our MySQL Database:

enter image description here

Now, as the question mentions, we need to find the sum of a particular column in a table. For example, let us add all the values of column "duration_sec" for the date '09-10-2018' and only status 'off'

For this condition, the following would be the sql query and code:

$sql_qry = "SELECT SUM(duration_sec) AS count 
    FROM tbl_npt 
    WHERE date='09-10-2018' AND status='off'";

$duration = $connection->query($sql_qry);
$record = $duration->fetch_array();
$total = $record['count'];

echo $total;

I have replace your Code and it works well

$sum=0;
while ($row = mysql_fetch_assoc($result)){
    $value = $row['Value'];

    $sum += $value;
}

echo $sum;

$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);

$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
    $qty += $num['ColumnName'];
}
echo $qty;

$result=mysql_query("SELECT SUM(column) AS total_value FROM table name WHERE column='value'");
$result=mysql_result($result,0,0);

MySQL 5.6 (LAMP) . column_value is the column you want to add up. table_name is the table.

Method #1

$qry = "SELECT column_value AS count
        FROM table_name ";

$res = $db->query($qry);

$total = 0;
while ($rec = $db->fetchAssoc($res)) {
    $total += $rec['count'];
}
echo "Total: " . $total . "\n";

Method #2

$qry = "SELECT SUM(column_value) AS count 
        FROM table_name ";

$res = $db->query($qry);

$total = 0;
$rec = $db->fetchAssoc($res);
$total = $rec['count'];

echo "Total: " . $total . "\n";

Method #3 -SQLi

$qry = "SELECT SUM(column_value) AS count 
        FROM table_name ";

$res = $conn->query($sql);

$total = 0;
$rec = row = $res->fetch_assoc();
$total = $rec['count'];

echo "Total: " . $total . "\n";

Method #4: Depreciated (don't use)

$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name'); 
$row = mysql_fetch_assoc($res); 
$sum = $row['count'];