Store Sum Of SQL Select in Variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
warrenk
Forum Newbie
Posts: 13
Joined: Wed Nov 01, 2006 8:46 am

Store Sum Of SQL Select in Variable

Post 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
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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?
warrenk
Forum Newbie
Posts: 13
Joined: Wed Nov 01, 2006 8:46 am

Post 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]
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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);
warrenk
Forum Newbie
Posts: 13
Joined: Wed Nov 01, 2006 8:46 am

Post by warrenk »

Thanks Volka....appreciate your help! :D
Post Reply