dubc07 Posted November 6, 2009 Share Posted November 6, 2009 I'm trying to get the total for each product and add them for a Grand Total to list outside the loop or only echo once I can do the addition but it will echo 5 time in the loop. How would I go about doing this? Thanks in advance for your help. <?php $cart2="SELECT * FROM products WHERE pro_indid='glass'"; $res2 = mysql_query($cart2) or die('Error, query failed 2'); while($cr2=mysql_fetch_array($res2)){ $totrow=$cr2["total"]; ///the $totrow will echo below 5 time each price in database 5.67 which the total should be 28.35 // echo $totrow; } ///Output of total would be $28.35 ?> The output I'm looking for would be like so 5.67 5.67 5.67 5.67 5.67 GrandTotal:28.35 Quote Link to comment https://forums.phpfreaks.com/topic/180516-solved-get-total-from-while-loop/ Share on other sites More sharing options...
mikesta707 Posted November 6, 2009 Share Posted November 6, 2009 $totrow = 0 while($cr2=mysql_fetch_array($res2)){ $totrow+=$cr2["total"]; ///the $totrow will echo below 5 time each price in database 5.67 which the total should be 28.35 // echo $cr2["total"]; } echo "total: $totrow"; Quote Link to comment https://forums.phpfreaks.com/topic/180516-solved-get-total-from-while-loop/#findComment-952328 Share on other sites More sharing options...
dubc07 Posted November 6, 2009 Author Share Posted November 6, 2009 Wish i could say that this worked but it only gave me a single value Quote Link to comment https://forums.phpfreaks.com/topic/180516-solved-get-total-from-while-loop/#findComment-952332 Share on other sites More sharing options...
ngreenwood6 Posted November 6, 2009 Share Posted November 6, 2009 This should work: <?php $cart2="SELECT * FROM products WHERE pro_indid='glass'"; $res2 = mysql_query($cart2) or die('Error, query failed 2'); $total = 0; //initialize the total while($cr2=mysql_fetch_array($res2)){ echo $cr2['total'].'<br>'; //show each total with a break $total += $cr2['total']; //add the value of the row to the total } echo $total; //show the total ?> Quote Link to comment https://forums.phpfreaks.com/topic/180516-solved-get-total-from-while-loop/#findComment-952348 Share on other sites More sharing options...
dubc07 Posted November 6, 2009 Author Share Posted November 6, 2009 Thanks for all your help this function works great. Quote Link to comment https://forums.phpfreaks.com/topic/180516-solved-get-total-from-while-loop/#findComment-952558 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.