How to get total in loop?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Bbob
Forum Commoner
Posts: 57
Joined: Sat Aug 07, 2010 4:46 am

How to get total in loop?

Post by Bbob »

Hi how do I get the total(sum of qty * price of all items) in this loop?

In this example I need to get...$total = 340

table structure:
id | name | qty | price
1 | php | 5 | 20
2 | js |10 | 30
3 | html |1 | 40

Code: Select all

while($row = mysql_fetch_assoc($get))
{
   <tr> 
      <td>$row['name']</td>
      <td>$row['qty']</td>
      <td>$row['price']</td>
     <td>$row['qty'] * $row['price'] </td>
   </tr>
}

<tr>
   <td colspan=4>$total</td>
</tr>
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: How to get total in loop?

Post by Christopher »

There are several ways to produce output with PHP -- either using echo or embedding <?php ?> blocks in HTML. Read the language part of the manual to learn the details.

Code: Select all

$grand_total = 0;
while($row = mysql_fetch_assoc($get))
{
     $total = $row['qty'] * $row['price'];
     $grand_total += $total;
echo "<tr> 
      <td>{$row['name']}</td>
      <td>{$row['qty']}</td>
      <td>{$row['price']}</td>
     <td>$total</td>
   </tr>";
}

echo "<tr>
   <td colspan=4>$grand_total</td>
</tr>";
[/quote]
(#10850)
User avatar
greyhoundcode
Forum Regular
Posts: 613
Joined: Mon Feb 11, 2008 4:22 am

Re: How to get total in loop?

Post by greyhoundcode »

Bbob wrote:Hi how do I get the total(sum of qty * price of all items) in this loop?

Code: Select all

$totalQty = 0;

while($row = mysql_fetch_assoc($get))
{
    $total     = $row['qty'] * $row['price'];
    $totalQty += $total;

    // (Code to output the table row ...)
}

echo $totalQty;
Of course, you could also use a SQL query to get the total.

Code: Select all

SELECT SUM(`qty`) FROM `tablename` WHERE 1;
Edit :oops: I see this has been answered already!
Bbob
Forum Commoner
Posts: 57
Joined: Sat Aug 07, 2010 4:46 am

Re: How to get total in loop?

Post by Bbob »

Hi

Thanks for the reply its working now :D
Post Reply