Saturn
Saturn

Reputation: 18149

PHP mysqli_fetch_array supposedly getting a boolean

$result = mysqli_query($conn,"SELECT * FROM Players");
if ($result !== FALSE) {
    while($row = mysqli_fetch_array($result)) {
        $result = mysqli_query($conn,"UPDATE Players SET Score='$score' WHERE ID='$id'");
    }
}

This works. That is, the databse is indeed updated and everything is all cool.

But it throws a warning:

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given

If you search around, the explanation is that the query is failing - hence, it is returning FALSE, so you get the warning.

... But this doesn't make sense in my case. The query is not failing. When I run this script, my database is updated just fine. Besides, there is also a conditional checking if the result is a boolean before using mysqli_fetch_array, so technically this warning should never happen in the first place.

Whatever, the problem must be with $result. Let's do:

echo gettype($result);

Which results in

"object"

Well, this explains why is it passing the condition. However, this still won't explain why mysqli_fetch_array insists this is a boolean (because it isn't).

What is the problem, then?

Tested with PHP Version 5.3.24 and 5.4.19.

Upvotes: 2

Views: 329

Answers (3)

FMQB
FMQB

Reputation: 673

The $result array returns nothing when you are updating the table. That's why, you are getting this warning in the while loop when it is trying to fetch data from $result into $row.

Upvotes: 1

Jigisha Variya
Jigisha Variya

Reputation: 207

In while loop used Same variable name '$result' which are already used before. Change variable name inside loop.

while($row = mysqli_fetch_array($result)) { $result = mysqli_query($conn,"UPDATE Players SET Score='$score' WHERE ID='$id'"); }

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212442

You're overwriting the resultset $result from your SELECT query with a new $result value from the UPDATE query inside your loop

while($row = mysqli_fetch_array($result)) {
    $result2 = mysqli_query($conn,"UPDATE Players SET Score='$score' WHERE ID='$id'");
}

Upvotes: 7

Related Questions