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;
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,...
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];
MySQL SUM() FunctionThe SUM() function calculates the sum of a set of values. Note: NULL values are ignored.
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') .
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'];
$query = "SELECT * FROM tableName"; $query_run = mysql_query($query); $qty= 0; while ($num = mysql_fetch_assoc ($query_run)) { $qty += $num['ColumnName']; } echo $qty;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With