开发者

How to loop through array from a query to return the total?

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 = $c开发者_C百科ost + $cost['total_cost'];
endforeach;

echo $cost;

That didn't work...

Any idea why?


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 .


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜