1

I am trying to get the total number from the database. Here is the current setup.

I have many records with a column named total_cost (decimal field) and I wrote a select statement to select all total_cost and put it in an array named $total_cost.

Now I am trying to add all the cost together to get the sum and I try it with this.

foreach ($total_cost as $cost) :
$cost = $cost + $cost['total_cost'];
endforeach;

echo $cost;

That didn't work...

Any idea why?

2 Answers 2

3

You don't need to use a loop , you can retrive the total cost straight from the mysql server like this

SELECT sum(total_cost) AS total_cost FROM tbl_name WHERE conditions ...

The above will sum up total_cost for fields who meet the conditions and return it so you don't have to loop in php .

Why do i recomend using this ? let's say you have 2Mil records and you whant to know a total cost , you're current setup will request 2Mil costs , hold them up in memory and loop thru them . Not realy eficient is it ? when you could get the sum straight from mysql so you don't have to hold a 2Mil key array in memory .

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, how do I use that total_cost there after? Does it become a PHP variable? so I can say echo $total_cost?
just like how the mysql returns an array full of ids , you'll get only one variable
2

The problem with your current code is that $code gets overwritten at the start of each loop iteration. To fix this store your running total in a different variable:

$result = 0;
foreach ($total_cost as $cost) :
$result += $cost['total_cost'];
endforeach;

echo $result;

1 Comment

Geez...everytime so close but yet so far...I don't know why I don't see those things...damn beginners...hehe...thanks, you are right on the money!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.