Patrioticcow
Patrioticcow

Reputation: 27058

php, how to calculate the sum from an while loop?

i have a while loop that returns some values:

while ($get_keywords3 = mysql_fetch_array($keywords2)){ 
?>
<tr>
<td><span style="margin: 0 3px;"><?php echo $get_keywords3['grand_total'];?></span></td>
</tr>

<?php } 

this returns back:

123
234
345
456
...

what i want is to add those together: 123 + 234 + 345 + ...

any ideas?

thanks

Upvotes: 0

Views: 12979

Answers (3)

Tarique Mosharraf
Tarique Mosharraf

Reputation: 1

//To get Project Data
echo "<table>";
echo "<tr>";
echo "<th> Project Code </th>  <th>Project Name</th> <th>Contract Amount </th> <th>Total Paid </th><th>Balance Amount </th>";
echo "</tr>";



while ($voucher_data = mysql_fetch_assoc($voucher_query)) {
        $pid = $voucher_data['pid'];
    $project_data = mysql_fetch_assoc(mysql_query("SELECT * FROM `projectinfo` WHERE `id`='$pid'"));

echo "<tr>";
    echo "<td>".$project_data['project_code']."</td>";
    echo "<td>".$project_data['Project_name']."</td>";
    echo "<td> TK.".$opening_bl = $voucher_data['opening_balance']."</td>";
    echo "<td> TK.".$paid = $voucher_data['SUM(current_pay)']."</td>";
    echo "<td> TK.". $pabe = $opening_bl - $paid."</td>";
echo "</tr>";

?>
</div>
<?php
@$sum_op += $opening_bl;
@$sum_paid += $paid;
@$sum_pabe += $pabe;
}

echo "<tr>";
    echo "<td>Total</td>";
    echo "<td></td>";
    echo "<td> TK.".$sum_op."</td>";
    echo "<td> TK.".$sum_paid."</td>";
    echo "<td> TK.". $pabe = $opening_bl - $sum_pabe."</td>";
echo "</tr>";
echo "</table>";

    echo "<br/>";

Upvotes: 0

grep
grep

Reputation: 4026

$sum = 0;
while ($get_keywords3 = mysql_fetch_array($keywords2)){ 
?>
<tr>
<td><span style="margin: 0 3px;"><?php echo $get_keywords3['grand_total'];?></span></td>
</tr>
<?php 
$sum += $get_keywords3['grand_total']; 
} 

echo $sum; //This will be your total after the adding.

This outta do it.

Upvotes: 3

Vincent Savard
Vincent Savard

Reputation: 35947

Either make a separate variable and do the sum in the while book ($var += $get_keywords3['grand_total'];) or make the sum in your query if you only want to sum (SELECT SUM(grand_total) -- etc).

Upvotes: 6

Related Questions