Oscar
Oscar

Reputation: 1103

How to select from mysql record then add the amount together?

What I try to ask is how to select from database record and my php code add the amount together.

here is my select mysql part:

$query= mysql_query("SELECT amount FROM item");
while($res=mysql_fetch_array($query)){
$totalamount= $res['amount'];
echo $totalamount;
}

my database got 4 records so it echo out is 1.002.003.001.50 , also as know as 1.00 2.00 3.00 1.50

I must using loop because it got a lot records in my database,so how can I add all this echo out answer become 7.80?

Thanks

Upvotes: 0

Views: 169

Answers (2)

Waseem Ahmad
Waseem Ahmad

Reputation: 303

Try This

$query= mysql_query("SELECT amount FROM item");
        $totalamount=0;
        while($res=mysql_fetch_array($query))
        {
        $tableamount= $res['amount'];
        $totalamount=$totalamount+$tableamount;
        }
        echo $totalamount;

Upvotes: 0

Alexa Adrian
Alexa Adrian

Reputation: 1858

Why don't you try to do like this:

SELECT SUM(amount) as total_ammount from item

Is this what you need? btw: you should not use loop, because it will take a lot of time for rendering, especialy if you want just the ammount ;)

Upvotes: 7

Related Questions