Canman2005 Posted April 22, 2006 Share Posted April 22, 2006 Dear allI have the following sql statement[code]<?$sql ="SELECT * FROM log WHERE code = '".$_SESSION['code']."'";$result = @mysql_query($sql,$connection) or die(mysql_error()); while ($rows = mysql_fetch_array($result)) { print "$rows[id]<br>"; }?>[/code]Which is fine and currently produces the following100300250150800How can I get it to add up all these numbers and come up with the final number, it would look like100+300+250+150+800which would produce 1600Any ideas?Thanks in advanceEd Quote Link to comment https://forums.phpfreaks.com/topic/8110-adding-sql-result-numbers/ Share on other sites More sharing options...
Tim Posted April 22, 2006 Share Posted April 22, 2006 I believe this would work:[code]<?$sql ="SELECT * FROM log WHERE code = '".$_SESSION['code']."'";$result = @mysql_query($sql,$connection) or die(mysql_error());$sum = 0;while ($rows = mysql_fetch_array($result)){ print "$rows[id]<br>"; $sum += $rows['id']; //add this number to the sum.}?>// $sum now equals 1600.[/code] :D Quote Link to comment https://forums.phpfreaks.com/topic/8110-adding-sql-result-numbers/#findComment-29609 Share on other sites More sharing options...
kenrbnsn Posted April 22, 2006 Share Posted April 22, 2006 Another way is to use MySql to get the total, assuming you don't want to print each number.[code]<?php$sql ="SELECT sum(id) as total_id FROM log WHERE code = '".$_SESSION['code']."'";$result = @mysql_query($sql,$connection) or die(mysql_error());$row = mysql_fetch_array($result);echo 'Total: ' . $row['total_id'];?>[/code]Ken Quote Link to comment https://forums.phpfreaks.com/topic/8110-adding-sql-result-numbers/#findComment-29615 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.