Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.