Jump to content

Adding numbers returned from MySQL query


galvin

Recommended Posts

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:)



						}

					}

 

 

Link to comment
Share on other sites

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;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.