woolyg Posted April 23, 2009 Share Posted April 23, 2009 Hi all, Is there a way to grab variables as a WHILE loop passes, and add them up to form a total at the end of the loop? For example: <?php //Get player_id $get_id = " SELECT players.player_id FROM players WHERE players.player_id='1' OR players.player_id='64' OR players.player_id='154' "; $run_id = mysql_query($get_id); while($display_id = mysql_fetch_assoc($run_id)){ // WHILE 130 $player_id = $display_id['player_id']; //Get the value of this player's speed $get_speed = " SELECT player_info.speed FROM player_info WHERE player_info.player_id='$player_id' "; $run_speed = mysql_query($get_speed); $display_speed = mysql_fetch_assoc($run_speed); $player_speed = $display_speed['speed']; } // WHILE 130 $total_speed_of_all_players = //???????? ?> I hope this is clear enough. Can anyone shed any light? Thanks, WoolyG Quote Link to comment https://forums.phpfreaks.com/topic/155302-solved-summing-variables-through-different-iterations-of-a-while-loop/ Share on other sites More sharing options...
JasonLewis Posted April 23, 2009 Share Posted April 23, 2009 Yeah, put the numbers into an array, then at the end use array_sum to calculate the total. Or you can have a running total going. $total = 0; while(loop){ $total += 5; } Just an example. It just adds 5 to $total after each loop, but you could use your variable there. Quote Link to comment https://forums.phpfreaks.com/topic/155302-solved-summing-variables-through-different-iterations-of-a-while-loop/#findComment-817053 Share on other sites More sharing options...
Maq Posted April 23, 2009 Share Posted April 23, 2009 Why can't you just use SUM() in your query? I also don't know why you're grabbing player_id from this query, putting it in a variable then running a while loop when you can just JOIN the two tables together. Quote Link to comment https://forums.phpfreaks.com/topic/155302-solved-summing-variables-through-different-iterations-of-a-while-loop/#findComment-817055 Share on other sites More sharing options...
woolyg Posted April 23, 2009 Author Share Posted April 23, 2009 ProjectFear - Perfect! Works like a charm. Thank you so much. Maq - I didn't do it that way because the original player_id's are variables from a previous query (inside another WHILE loop again), and didn't want to make my post more convoluted than necessary... Cheers, WoolyG Quote Link to comment https://forums.phpfreaks.com/topic/155302-solved-summing-variables-through-different-iterations-of-a-while-loop/#findComment-817058 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.