0

This is my code that I am using to try and calculate the sum of "amountReceived" column. The total for invID '95' should = 312, but for some reason it is only = 300. I am not sure what the issue is. (please see the DB images below).

$sql = mysql_query("SELECT amountReceived FROM payments WHERE invID='".$id."'");
$result = mysql_fetch_array($sql);
$totalPayment = array_sum($result);
$balanceDue = $invoiceTotal - $totalPayment;

enter image description here

enter image description here

1
  • Because you only fetched one row... Commented Jul 17, 2012 at 1:42

3 Answers 3

7

How about using SUM()?

$sql = mysql_query("SELECT SUM(amountReceived) FROM payments WHERE invID='".$id."'");
$totalPayment = mysql_fetch_row($sql);
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this before and it is not working. I am just not sure what the issue is.
3

well the mysql_fetch_array($sql) returns an array containing all "columns" of one row you fetched, means you get an e.g. array('amountReceived'=>150)

this should work:

$sql = mysql_query("SELECT amountReceived FROM payments WHERE invID='".$id."'");
$totalPayment = 0;
while($result = mysql_fetch_array($sql)) {
    $totalPayment += $result['amountReceived'];
}
$balanceDue = $invoiceTotal - $totalPayment;

this is just a php side description of the problem, if you want to be more efficient, use sel's version ;)

1 Comment

It would be much more efficient to use the aggregate functions within the database to get the totals needed.
0
  1. Don't use mysql_* functions - use MySQLi or PDO.
  2. print_r($result); to see if there's something inside.

1 Comment

Don't forget you can inline code highlight with the backticks (`) and link to useful resources

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.