Page 1 of 1

SUM function problem

Posted: Tue Aug 03, 2010 9:44 am
by adsegzy
Hello friends,

am having problem with my SUM function. I tried summing up some figures in a column but is not returning the total of the figures. this is my syntax

Code: Select all

<?php
include("config.php");
$column='amount';
$table='transactions'
$creditbal=mysql_query("SELECT SUM($colunm), FROM $table WHERE status='P'");
echo $creditbal;
?>
but is not echoing any out any, what can i do.

Regards,
adsegzy

Re: SUM function problem

Posted: Tue Aug 03, 2010 9:47 am
by jraede
You spelled "column" two different ways...is that the problem?

Re: SUM function problem

Posted: Tue Aug 03, 2010 9:49 am
by jraede
Oh, and also you should look up what mysql_query does...it doesn't return a string that you can just echo. You have to retrieve the data somehow with mysql_fetch_array, mysql_fetch_row, etc, depending upon how you want to work with it.

Re: SUM function problem

Posted: Wed Aug 04, 2010 4:36 am
by adsegzy
Well i have corrected the colunm error and have rewritten it as below but it's not still echoing out my sum

Code: Select all

<?php
include("config.php");
$column='amount';
$table='transactions'
$creditbal=mysql_query("SELECT SUM($column), FROM $table WHERE status='P'");
$rows=mysql_fetch_array($creditbal);
echo $rows[$creditbal];
?>
but still not working. any other way out?

Re: SUM function problem

Posted: Wed Aug 04, 2010 4:55 am
by Eran
Are you a programmer? $rows is an array, you can't echo it.

Re: SUM function problem

Posted: Wed Aug 04, 2010 5:00 am
by jraede
Without looking it up, I'm also fairly certain that SUM is a group function, in which case you would need GROUP BY syntax at the end of your query. So in this case it would be "GROUP BY `status`".

And you are trying to access the value in the $rows array with the key that corresponds to your query object?? That makes no sense...in this case, since you're not giving SUM($column) a name, you'd have to $rows[0] to get the first returned value, which is the result of the SUM function.

Re: SUM function problem

Posted: Wed Aug 04, 2010 6:50 am
by Eran
You can use SUM() without a GROUP BY modifier

Re: SUM function problem

Posted: Wed Aug 04, 2010 6:58 am
by superdezign
Am I the only one suspicious about the comma after the SUM() function? Have you tried echoing mysql_error(), yet?

Re: SUM function problem

Posted: Wed Aug 04, 2010 7:02 am
by Eran
Yes, that comma shouldn't be there