Jump to content

[SOLVED] Total the value of all rows contents of a specific column in a database query


jaxdevil

Recommended Posts

What I am trying to do is query my database, pull all the rows that match to a specific bill, and total the values of the 'dollar amount' column ($num_amt in the query below) to determine the total dollar amount paid towards that specific bill. I cannnot figure out how to do this. Any ideas?

 

Here is my code:

 

$paid_lookup = mysql_query("SELECT * FROM `check_database` WHERE `bill_code` = '$bill_code'") or die('MySQL Connection Error:'.mysql_error());
while($paid = mysql_fetch_array($paid_lookup)){
$amount_paid = $paid[num_amt];
}

 

Thanks,

SK

use sum

you should be able to fiqure it from this example code

 

<?php
// Make a MySQL Connection

$query = "SELECT type, SUM(price) FROM products GROUP BY type"; 

$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['type']. " = $". $row['SUM(price)'];
echo "<br />";
}
?>



Non-SQL version

$paid_lookup = mysql_query("SELECT * FROM `check_database` WHERE `bill_code` = '$bill_code'") or die('MySQL Connection Error:'.mysql_error());
$amount_paid = 0;
while($paid = mysql_fetch_array($paid_lookup)){
$amount_paid =  $amount_paid + $paid[num_amt];
}

 

SQL Version:

$paid_lookup = mysql_query("SELECT SUM(num_amt) FROM `check_database` WHERE `bill_code` = '$bill_code'") or die('MySQL Connection Error:'.mysql_error());
$amount_paid = 0;
while($paid = mysql_fetch_array($paid_lookup)){
$amount_paid =  $paid[num_amt];
}

 

I am unsure if the SQL version will work, I think it will but yea.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.