Page 1 of 1

How to get total in loop?

Posted: Sun Nov 21, 2010 1:13 pm
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>

Re: How to get total in loop?

Posted: Sun Nov 21, 2010 1:54 pm
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]

Re: How to get total in loop?

Posted: Sun Nov 21, 2010 1:57 pm
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!

Re: How to get total in loop?

Posted: Fri Nov 26, 2010 7:26 am
by Bbob
Hi

Thanks for the reply its working now :D