Jump to content

[SOLVED] SUMming variables through different iterations of a WHILE loop?


Recommended Posts

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

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.

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.

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.