0

I'm trying to get the sum of a column.

My Schema is as below...

scheme screen shot

I'd like to get the SUM of 'bill'.

I have the following...

   <?php
   $uid = $_SESSION['oauth_id'];
   $query = mysql_query("SELECT * FROM `users`, `income`, `outgoings` WHERE users.oauth_uid = '$uid' and income.user_id = '$uid' and outgoings.user_id = '$uid'") or die(mysql_error());
   $result = mysql_fetch_array($query);
   ?>

   Outgoings = <?php echo $result["SUM(total)"];

I'm not receiving any output, however. Can anybody see where I'm going wrong? There's definitely data in my table.

5
  • 5
    because $result has no index SUM(total) Commented Apr 12, 2012 at 21:28
  • 1
    What Jack said. Write your SQL in the SQL query. Commented Apr 12, 2012 at 21:29
  • Why are you bringing the world to you? do you use everything you get? else you could only do SELECT sum(bill) FROM users. Commented Apr 12, 2012 at 21:30
  • Im using everything yes, im new to PHP, is this bad practice? Commented Apr 12, 2012 at 21:31
  • No, AFAIK this is not a bad practice. Commented Apr 12, 2012 at 21:35

4 Answers 4

1

The SUM function must be used when deciding what to return from the select. Like so.

   SELECT SUM(`bill`) FROM `users`, `income`, `outgoings` WHERE users.oauth_uid = '$uid' and income.user_id = '$uid' and outgoings.user_id = '$uid'
Sign up to request clarification or add additional context in comments.

Comments

1

Try this if you don't want to do a SUM() query as already proposed by others:

<?php
$sum = 0;
while ($row = mysql_fetch_array($query)) {
    $sum += $row['bill'];
}
?>
Outgoings = <?php echo $sum; ?>

But remember that you will need this if you want to reuse the same $query resultset:

<?php
     mysql_data_seek($query , 0);
?>

Comments

0

Why not just query for the SUM directly? Like:

   <?php
       $uid = $_SESSION['oauth_id'];
       $sum = mysql_query("SELECT SUM(`bill`) FROM `users` WHERE users.oauth_uid = '$uid'") or die(mysql_error());
   ?>

Comments

0

This query will get you the sum:

SELECT sum(bill) FROM `the_table`

Comments

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.