galvin Posted September 19, 2011 Share Posted September 19, 2011 Say I do a query from a database that only asks for one field in return (which always has a number in it). How do you write the PHP to take the first number returned and add it to the next number returned (NOTE: There may be more than two numbers returned, but for now, I'm always dealing with two) For example, say I do a query that returns the number 27 first and then the number 10 second. FYI, these numbers will be available in the variable $diff['result']. So the code after the query would look something like this, but obviously i'm struggling with the part in comments... if (!$numbers) { die("Database query failed: " . mysql_error()); } else { while ($diff = mysql_fetch_array($numbers)) { //this would bring back 27 first, in the variable $diff['result'] and then on the 2nd loop through, it would bring back 10 in the $diff['result'] variable //ultimately, i just want the difference between the numbers (which in the case would be 17). It's just a simple addition, so Im obviously an idiot because I can't figure out the syntax for adding the first returned number to the next returned number:) } } Quote Link to comment https://forums.phpfreaks.com/topic/247400-adding-numbers-returned-from-mysql-query/ Share on other sites More sharing options...
xyph Posted September 19, 2011 Share Posted September 19, 2011 So you want to subtract, not add? Here's the solution with arrays. It is easily adapted to fit into your code $array = array(27,10,5); $total = FALSE; foreach( $array as $num ) { if( $total === FALSE ) // Check if $total hasn't been set yet (first loop) $total = $num; // Set total as number else // otherwise $total -= $num; // Subtract number from total } echo $total; Quote Link to comment https://forums.phpfreaks.com/topic/247400-adding-numbers-returned-from-mysql-query/#findComment-1270518 Share on other sites More sharing options...
galvin Posted September 19, 2011 Author Share Posted September 19, 2011 Yes, I meant subtract, sorry Anyway, your info helped me make it do what I needed, thank you so much! Quote Link to comment https://forums.phpfreaks.com/topic/247400-adding-numbers-returned-from-mysql-query/#findComment-1270528 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.