Adding together multiple values of a variable

Can somebody tell me how to add multiple values of the same variable together please.

My code is like this to get variables from database

while ($getarea = @mysql_fetch_array($areasql))	{
$area = $getarea['area'];

$area can be a single or multiple result which has to be added together to give $totalarea;

for example area1 = 2, area2 = 4, totalarea =6

Or would it be easier to get mysql to do it and if so how?

SELECT SUM(area) AS total_area FROM table

Yup, it’s simpler, quicker and much clearer asking your db for the total. :slight_smile:

If you have to already loop for displaying the record, then don’t go for running another query because simply adding values would work perfectly i guess and would be faster, quicker too. So I hope if I have understood your question, something like this would work for you:


$totalaray = 0;
while ($getarea = @mysql_fetch_array($areasql)) {
	$area = $getarea['area'];
	$totalaray += $area;
}
echo 'Total Area : ' . $totalaray;

Hey Rajug,

the OP would just add SUM(area) AS total_area to his already existing query thus negating the need to run another query.

Oh Yes Anthony if OP has understood in that way and can integrate your query to his existing query. Otherwise my solution would also work I think.

Thanks to both. I think mysql query fits the bill for what I need, and as usual the answer was staring me in the face!! Just coudn’t see it!

I agree with Anthony, getting the answer from the db is more effective and consumes only one call/session (essential if running multi-tier over a crowded backend)