Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sum of MySQL column in PHP

Tags:

php

mysql

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; 
like image 388
jack Avatar asked Apr 27 '11 18:04

jack


People also ask

How can I get column sum in MySQL using PHP?

MySQL is a database query language for managing databases. sum() function is an aggregation operation used to add the particular column based on the given condition. Syntax: SELECT SUM(column1),column2,...

How do I total a column in PHP?

With this article, we'll look at some examples of how to address the Calculate Sum (Total) Of Column In Php problem . mysql_connect($hostname, $username, $password); mysql_select_db($db); $sql = "select sum(column) from table"; $q = mysql_query($sql); $row = mysql_fetch_array($q); echo 'Sum: ' . $row[0];

How do I sum a query in MySQL?

MySQL SUM() FunctionThe SUM() function calculates the sum of a set of values. Note: NULL values are ignored.

How do I display the sum of two columns in MySQL?

MySQL SUM() function retrieves the sum value of an expression which is made up of more than one columns. The above MySQL statement returns the sum of multiplication of 'receive_qty' and 'purch_price' from purchase table for each group of category ('cate_id') .


2 Answers

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']; 
like image 146
Flinsch Avatar answered Sep 19 '22 07:09

Flinsch


$query = "SELECT * FROM tableName"; $query_run = mysql_query($query);  $qty= 0; while ($num = mysql_fetch_assoc ($query_run)) {     $qty += $num['ColumnName']; } echo $qty; 
like image 25
Alex Avatar answered Sep 19 '22 07:09

Alex