joecooper Posted August 25, 2011 Share Posted August 25, 2011 Hi, I have a database with some rows. in each row there is a number such as: 0.0023 or 0.0135... I have the following code to loop though them and add the numbers up but it always returns 0? $sql="SELECT * FROM tickets WHERE `round` = '$round' AND `confirmed` = 'yes' ORDER BY id ASC"; $result=mysql_query($sql); $row=mysql_fetch_array($result); while($row = mysql_fetch_array( $result )) { $balance = $balance + $row['amount']; } Link to comment https://forums.phpfreaks.com/topic/245648-loop-though-db-adding-values/ Share on other sites More sharing options...
jcbones Posted August 25, 2011 Share Posted August 25, 2011 Is the amount column a float? $sql="SELECT SUM(`amount`) AS total FROM tickets WHERE `round` = '$round' AND `confirmed` = 'yes' ORDER BY id ASC"; $result=mysql_query($sql); $row=mysql_fetch_array($result); while($row = mysql_fetch_array( $result )) { echo $row['total']; } Link to comment https://forums.phpfreaks.com/topic/245648-loop-though-db-adding-values/#findComment-1261652 Share on other sites More sharing options...
trq Posted August 25, 2011 Share Posted August 25, 2011 You should do this in your query not php. Mysql has a SUM() function. Link to comment https://forums.phpfreaks.com/topic/245648-loop-though-db-adding-values/#findComment-1261653 Share on other sites More sharing options...
joecooper Posted August 25, 2011 Author Share Posted August 25, 2011 ah thats it. although i have done away with the "while" altogether. also forgot to set the feild to FLOAT. Just quickly, how to format this to 8 decimal places? Link to comment https://forums.phpfreaks.com/topic/245648-loop-though-db-adding-values/#findComment-1261657 Share on other sites More sharing options...
joecooper Posted August 25, 2011 Author Share Posted August 25, 2011 done it with number_format Thanks! Link to comment https://forums.phpfreaks.com/topic/245648-loop-though-db-adding-values/#findComment-1261659 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.