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



						}

					}

 

 

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;

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.