Jump to content

Doing simple math inside while loop


dubc07

Recommended Posts

What i'm trying to do is pull from a table the amount for each record associated to an id number and add them together.

Below shows what i have so far which is not even a start.

 

<?php
$sub = mysql_query('SELECT * FROM guestpayment WHERE sponsorid="'.$_SESSION['sponsorid'].'"');
     while($subrow = mysql_fetch_array($sub))
     {
         
	 $amount= $subrow['amount'];
                 $fname=$subrow['fname'];

$totamount=$amount + $amount;

echo "Firstname: $fname Total Amount: $totamount<br><br>";



}

?>

 

I have two rows in the table with the same user "Jane"

 

The above code will output the following:

Firstname: Jane Total Amount: 60.00 <----This adds 30.00 twice which is not what im needing to do.

Firstname: Jane Total Amount: 240.00<------This adds 120.00 Twice

 

The output im looking to get is the following:

 

Firstname: Jane Total Amount: 150.00<-------This would just add the two numbers from each table 30.00 and 120.00

and this would just echo one row instead of 2 for each entry on he table.

 

Any help is appreciated Thanks

 

Link to comment
https://forums.phpfreaks.com/topic/177921-doing-simple-math-inside-while-loop/
Share on other sites

Hi

 

Let SQL take the strain:-

 

<?php
$sub = mysql_query('SELECT fname, SUM(amount) AS totamount FROM guestpayment WHERE sponsorid="'.$_SESSION['sponsorid'].'" GROUP BY fname');
while($subrow = mysql_fetch_array($sub))
{
echo "Firstname: ".$subrow['fname']." Total Amount: ".$subrow['totamount']."<br><br>";
}
?>

 

Although this will only work if the first name is unique.

 

All the best

 

Keith

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.