ngreenwood6 Posted October 10, 2008 Share Posted October 10, 2008 I am trying to figure out how to add 2 rows from the database together. I have a database entry that is called amount. When i pull the information from the database I display it like this $row['amount']. I have more than one entry in the database and I want to be able to add them together. For example: //make the connection mysql_connect('localhost','user','pass'); mysql_select_db('database'); //make the query $query = "SELECT * FROM table"; //perform the query $results = mysql_query($query); //get the contents while($row = mysql_fetch_array($results)) { echo $row['amount']; echo "<br>"; } ?> Now if I wanted to add them how would I add all the amounts to get a total. I have tried this: $row_amount = $row['amount']; $total = $row_amount + $row_amount; echo $total; That is not correct though because when i echo the total it gives me the same amount plus the same amount instead of adding all of the amounts. Any help is appreciated. Quote Link to comment Share on other sites More sharing options...
budimir Posted October 10, 2008 Share Posted October 10, 2008 You can use SUM function in MYSQL $sql = "SELECT *, SUM(amount) as amount WHERE id = '$id' GROUP BY amount"; Something like that.. Work with it... Quote Link to comment Share on other sites More sharing options...
ngreenwood6 Posted October 10, 2008 Author Share Posted October 10, 2008 Thanks for the reply but is there anyway that I can do it using php instead of mysql. Quote Link to comment Share on other sites More sharing options...
budimir Posted October 10, 2008 Share Posted October 10, 2008 Of course, you can do it with PHP. Use counter!! Quote Link to comment Share on other sites More sharing options...
Barand Posted October 10, 2008 Share Posted October 10, 2008 I'd go for the MySQL SUM function too, however the php code you are using should be $total = 0; while($row = mysql_fetch_array($results)) { echo $row['amount']; echo "<br>"; $total += $row['amount']; // add row amount to total } echo "Total : $total"; Note: $total += $row['amount']; is a shorthand way of writing $total = $total + $row['amount']; Quote Link to comment Share on other sites More sharing options...
ngreenwood6 Posted October 10, 2008 Author Share Posted October 10, 2008 Thanks I had that but I was doing it inside of the while loop. just had it misplaced. Again thanks for the help. Quote Link to comment 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.