Kelly Ward
Kelly Ward

Reputation: 25

php while-loop only updating first row results

I want the cronjob function to update the money of all allusers2 by 1, instead only the first row is increased and increases by 9. (there are 10 users). I tried swapping the while loop for a for loop and had the same results. I tried turning $database->fetch into mysqli_fetch_array with the same results and turning it into mysqli_fetch_all gives me "Notice: Undefined index: //variable name\" for all database variables.

class allusers2
{
    public $id;
    public $level;
    public $money;
    private $database;

    // Methods (functions)
    public function __construct($allusers_id, $database)
    {
        $this->database = $database;
        $allusers_id = (int)$allusers_id;
        $result = $this->database->query("SELECT * FROM `users` WHERE `id`='$allusers_id'");
        if($this->database->num_rows($result) == 0) {
            throw new Exception("allusers does not exist!");
        }

        $allusers = $this->database->fetch($result);

        $this->id = $allusers['id'];
        $this->level = $allusers['level'];
        $this->money = $allusers['money'];

    }

    public function update()
    {

        $this->database->query("UPDATE `users` SET
            `level` = '{$this->level}',
            `money` = '{$this->money}'
            WHERE `id`='{$this->id}'");
    }
}

function cronjob()
{
    global $database;
    global $player;
    global $self_link;
    require('allusers2.php');
    $result = $database->query("SELECT id FROM `users`");
    $allusers_id = $database->fetch($result);
    $allusers2 = new Allusers2($allusers_id, $database);
    while($allusers_id = $database->fetch($result)) {

        $allusers2->money += 1;
        $allusers2->update();
    }
}

Upvotes: 2

Views: 106

Answers (2)

C3roe
C3roe

Reputation: 96306

If you really want to update all records, and increment the money by the same amount, then you don't need to select the records first and loop over them - the database can do that for you in one go:

UPDATE users SET money = money + 1

Upvotes: 1

aynber
aynber

Reputation: 23011

You're only ever updating the first user:

$result = $database->query("SELECT id FROM `users`");
$allusers_id = $database->fetch($result); // Extract the first user
$allusers2 = new Allusers2($allusers_id, $database); // Create object for first user
while($allusers_id = $database->fetch($result)) {

    $allusers2->money += 1; // Keep updating that first user
    $allusers2->update();
}

You need to not do the first fetch, and move the Allusers2 into the loop:

   while($allusers_id = $database->fetch($result)) {

        $allusers2 = new Allusers2($allusers_id, $database); // Now you're creating a new object for each user
        $allusers2->money += 1;
        $allusers2->update();
    }

Upvotes: 0

Related Questions