homepage Welcome to WebmasterWorld Guest from 54.205.188.59
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Adding together variables form an SQL select statement
ModernMerlin




msg:4462363
 9:00 am on Jun 7, 2012 (gmt 0)

What I am trying to do and for some reason am drawing a blank, is figure out how to pull several numbers from the same column in a table and add them together to get one final number for another math problem.

For example:
$query = mysql_query ("SELECT attr_amt FROM user_attr WHERE user_id = '".$user_id."'") or die(mysql_error());

And then I assume I would add a foreach but for some reason cannot for the life of me figure out how to add the numbers together. Perhaps its because its 2am lol.

For example lets say there are three entries in the table for that user.

Any ideas/suggestions/guidance would be greatly appreciated!

Thanks!

 

rlange




msg:4462474
 2:31 pm on Jun 7, 2012 (gmt 0)

It sounds like you want to use MySQL's SUM() function.

$result = mysql_query( "SELECT SUM( `attr_amt` ) AS `total` FROM `user_attr` WHERE `user_id` = '" . $user_id . "'" ) or die( mysql_error() );

echo $result['total'];


Other, non-essential changes in the above code:
  • Whitespace: The extra whitespace is just my personal coding convention.
  • Backticks (`): Using backticks around column and table names lets you use otherwise reserved keywords (e.g. `count`) or spaces and other characters (e.g. `dont do this` and `just,dont`). They're MySQL-specific, though.

ModernMerlin




msg:4463244
 3:23 am on Jun 9, 2012 (gmt 0)

That is exactly what I was looking for. Thank you so much!

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved