简体   繁体   中英

If statement in while loop not updating all users in database

Im trying to update all users in the database to get +5 turns every time this script is run.

But it updates only the first user in the database untill it has full turns and then it updates the next user.

What do i have to do to add 5 turns to all users but dont add any if they have 100/100 turns?

<?php

include ("functions/db_connect.php");

$get_users = mysqli_query($db, "SELECT * FROM `members`") or die(mysql_error());
while($user = mysqli_fetch_assoc($get_users)){

    if ($user['current_turns'] < $user['max_turns']) {
        $update = mysqli_query($db, "UPDATE `members` SET
                                `current_turns`=`current_turns`+'5' WHERE `id`='".$user['id']."'") or die(mysql_error());
        header("Location: users.php");
        exit();

    }
}

?>

Try using a query like this to update all the members at the same time instead of selecting them all and looping through updating them one by one.

UPDATE members 
SET current_turns = LEAST(max_turns, current_turns + 5)
WHERE current_turns < max_turns

Using the LEAST function will allow the current_turns to be incremented up to max_turns without going over, as I assume this would be undesirable, but it does depend on neither column being null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM