...

View Full Version : SUM() in php



Cmarenburg
01-28-2012, 07:51 PM
Hello there, i am trying to add the total amount of sales together here is what i have tried


<?php
$query = 'SELECT SUM(ammount) AS SalesTotal FROM Orders WHERE user_id=' .$user->data['user_id'];

$result = mysql_query('$query');

echo $result;
?>

and include it in page, but nothing is being echoed at all.

What did i do wrong?

Thanks!

Dan13071992
01-28-2012, 08:41 PM
Hello there, i am trying to add the total amount of sales together here is what i have tried


<?php
$query = 'SELECT SUM(ammount) AS SalesTotal FROM Orders WHERE user_id=' .$user->data['user_id'];

$result = mysql_query('$query');

echo $result;
?>

and include it in page, but nothing is being echoed at all.

What did i do wrong?

Thanks!

try this:



$row=mysql_fetch_assoc($query);
$sales=$row['SalesTotal'];


and echo it as $sales

Cmarenburg
01-28-2012, 09:11 PM
try this:



$row=mysql_fetch_assoc($query);
$sales=$row['SalesTotal'];


and echo it as $sales

Hey there, when i do that i am left with an error:

[phpBB Debug] PHP Warning: in file /var/www/includes/sales-total.php on line 4: mysql_fetch_assoc() expects parameter 1 to be resource, string given

Fou-Lu
01-28-2012, 09:15 PM
None of this will work. $query is not parsed within the mysql_query, it is a literal string so the query will fail.


$qry = mysql_query($query) or die(mysql_error());
$sales = mysql_result($qry, 0, 0);

Cmarenburg
01-28-2012, 09:18 PM
None of this will work. $query is not parsed within the mysql_query, it is a literal string so the query will fail.


$qry = mysql_query($query) or die(mysql_error());
$sales = mysql_result($qry, 0, 0);


Thank You soo much!

Dan13071992
01-28-2012, 10:03 PM
None of this will work. $query is not parsed within the mysql_query, it is a literal string so the query will fail.


$qry = mysql_query($query) or die(mysql_error());
$sales = mysql_result($qry, 0, 0);



sorry i forgot that it hadnt already gone through the mysql_query function, my mistake.

FL thanks for your inbox the other day, i got it working in the end.

back to the topic, im a bit confused as to what this function means, and how it works:



$sales = mysql_result($qry, 0, 0);


so just to help Cmarenburg and myself understand it better could you give us a bit of insight into how the mysql_result and the 0, 0 actually work/what they mean.

thanks.

Dan

Fou-Lu
01-29-2012, 05:44 PM
Mysql_result is used to pull single entries from the dataset. I wouldn't use it for anything more than say a count or sum or another aggregate, since it is slower than pulling from mysql_fetch, but saves you the memory of a variable assignment. 0, 0 is simply the row and the field, since PHP is 0 based its the first row and first column.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum