MySQL SUM (what am I doing wrong?)
Moderator: General Moderators
MySQL SUM (what am I doing wrong?)
I dont know what I'm doing wrong here. I've found this on about a million forums, etc. saying just put the sum in the SQL query and it returns the sum of a column. Can someone help me out here?
$total_paid = mysql_query( "SELECT sum(amount) FROM table" );
if i print that value it gives me some "resource id #7" (dont know) and if I put it into a mysql_fetch_array(); and use the php array_sum(); it gives me the number 1000 which isn't correct at all either. I dont know what I'm doing wrong.
$total_paid = mysql_query( "SELECT sum(amount) FROM table" );
if i print that value it gives me some "resource id #7" (dont know) and if I put it into a mysql_fetch_array(); and use the php array_sum(); it gives me the number 1000 which isn't correct at all either. I dont know what I'm doing wrong.
Try this.
This should work.
This should work.
Code: Select all
$sql = 'SELECT SUM(amount) AS total FROM `table`';
$result = mysql_query($sql) OR die(mysql_error());
if(mysql_num_rows($result)) {
while($row = mysql_fetch_assoc($result)) {
$total_paid = $row['total'];
echo $total_paid;
}
} else {
echo "No Data";
}- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
I'm saying that this..
Outputted:
Code: Select all
$Query = "select sum(`Rating`) from `table`";
$Execute = mysql_query($Query, $Connect);
$Count = mysql_fetch_assoc($Execute);
print_r($Count);Array ( [sum(`Rating`)] => 5 )
Ok so I tested it, and
outputs the sum, which is cool because I have never seen a key like that before. But now is there a way for me to find out how many rows it added together?
Code: Select all
echo $Count['sum(`Rating`)'];- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Not using SUM. You might be able to do a row_count code side, or COUNT() DB side, but trying to get the row count AND sum from the same query I don't think is going to happen.astions wrote:Ok so I tested it, and
outputs the sum, which is cool because I have never seen a key like that before. But now is there a way for me to find out how many rows it added together?Code: Select all
echo $Count['sum(`Rating`)'];