Get sum of MySQL column in PHP

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

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

Try this:

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

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'];

Tags:

Mysql

Php