Page 1 of 1

Store Sum Of SQL Select in Variable

Posted: Thu Nov 02, 2006 11:37 am
by warrenk
I have a SQL statement with 2 sums which I would like to place in variables. Question is...how do I place a sum in a variable?

Example:

$sql = "select sum(price), sum(quantity) * from orderfile";

I would like to place the sum or price in variable1 and sum of quantity in variable 2.

Thanks for any help!
Warren

Posted: Thu Nov 02, 2006 11:53 am
by volka
You send the statement to your database server and fetch the result like any other.
What database system do you use? What function to send the query do you use?

Posted: Thu Nov 02, 2006 11:59 am
by warrenk
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Here is how I normally retrieve a result....

Code: Select all

$sql = "select price, quantity from order";

$results = odbc_exec($conn, $sql);
while(odbc_fetch_row($results))
{

$f01  = odbc_result($results, "price");
$f02  = odbc_result($results, "quantity");

}
If I want to retrieve totals, would it be something like....

Code: Select all

$sql = "select sum(price), sum(quantity) from order";

$results = odbc_exec($conn, $sql);
while(odbc_fetch_row($results))
{

$f01  = odbc_result($results, "sum(price)");
$f02  = odbc_result($results, "sum(quantity)");

}

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Thu Nov 02, 2006 12:23 pm
by volka
You can either give the result fields new names

Code: Select all

SELECT sum(price) as sumprice, sum(quantity) as sumquantity FROM orde
or you access the fields by their position
http://de2.php.net/odbc_result wrote:field can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field.

Code: Select all

$f01 = odbc_result($results, 1);
$f02 = odbc_result($results, 2);

Posted: Thu Nov 02, 2006 12:25 pm
by warrenk
Thanks Volka....appreciate your help! :D