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
Bbob
Forum Commoner
Posts: 57 Joined: Sat Aug 07, 2010 4:46 am
Post
by Bbob » Sun Nov 21, 2010 1:13 pm
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>
Christopher
Site Administrator
Posts: 13596 Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US
Post
by Christopher » Sun Nov 21, 2010 1:54 pm
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)
greyhoundcode
Forum Regular
Posts: 613 Joined: Mon Feb 11, 2008 4:22 am
Post
by greyhoundcode » Sun Nov 21, 2010 1:57 pm
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 I see this has been answered already!
Bbob
Forum Commoner
Posts: 57 Joined: Sat Aug 07, 2010 4:46 am
Post
by Bbob » Fri Nov 26, 2010 7:26 am
Hi
Thanks for the reply its working now