Jump to content

[SOLVED] The loop doesnt loop


mingkus

Recommended Posts

I'm making a game and im making a code that gives every user energy at the same time. So I made a loop wanting it to give every user energy.  The code works, but the loop only updates the top user in the database.

 

$query = "SELECT * FROM `accounts`";
$result = mysql_query($query);
while($account = mysql_fetch_assoc($result)) {
$id = $account['id'];
$energy = $account['energy'];
$maxenergy = $account['maxenergy'];

$energy = $energy + (0.08 * $maxenergy);

$query = "UPDATE `accounts` SET `energy`='".$energy."' WHERE (id) = '".$id."'";
$result = mysql_query($query);
}

Link to comment
https://forums.phpfreaks.com/topic/121851-solved-the-loop-doesnt-loop/
Share on other sites

Do you want to give EVERY user energy or just the current user?

 

Cause it looks like that's a very big loop to do. One thing is that it will put HUGE stress on the server, performing quite a bit of queries.

 

If you want to do it this way, fix your inner variables. You change $query and $result inside the loop, which pretty much stops it.

 

$query = "SELECT * FROM `accounts`";
$result = mysql_query($query);
while($account = mysql_fetch_assoc($result)) {
$id = $account['id'];
$energy = $account['energy'];
$maxenergy = $account['maxenergy'];

$energy = $energy + (0.08 * $maxenergy);

$query2 = "UPDATE `accounts` SET `energy`='".$energy."' WHERE (id) = '".$id."'";
$result2 = mysql_query($query2);
}

Well, you're overwriting the variables, $query, and $result inside the loop, so those need different variable names in order to not overwrite.

 

And I'm almost positive that the following code would do the same thing:

 

$query = "UPDATE `accounts` SET `energy` = `energy`+(.08*`maxenergy`)";

 

He means that, before you begin the loop you have queried the database and stored the query inside two variables, $query and $result. Once you begin the loop, these variables are overwritten by the new query therefore overwriting the old query and stopping the loop.

 

Again, he is also right. Depending on the amount of users you have, updating every user would be a huge strain on the server. I would suggest only updating the current users' energy when they visit a page that displays their energy level, for example their statistics page. Make this energy increase periodically.

 

The user would be none the wiser, since it would all be happening behind the scenes. They will only know what they are told.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.