user1780242 user1780242 - 3 months ago 16
PHP Question

Why is fetch_assoc() not returning a value?

For the life of me I can't figure out why fetch_assoc() is returning false here:

$username = $_POST['username'];
print("Username is " . $username . "<br>");

//Create query
$query = ("SELECT * FROM users WHERE username = '" . $username . "'");
print($query . "<br>");

//Run query
if (!$result = $db2 -> query($query)) {
print("Query failed!");
}

if (!$user = new LG_User($result))
print("Failed to create user!<br>");

while($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
var_dump($rows);
print("User is " . $user -> first_name . "<br>");


The query is successful and the new user object is created, because the last line of code is printing $user->first_name correctly. I'm using the very same block of code to populate the $rows array on another page and it is working. What am I doing wrong here? If I try to use

while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}


instead of

while($row = $result -> fetch_assoc()) {
$rows[] = $row;
}


it still doesn't work. What am I missing here?

Answer

You haven't shown the code for the LG_User constructor, but if it's filling in $user from the database, it must be calling a fetch function itself. So when it returns, all the rows of the result have been fetched, and there's nothing left for your loop to read.

You can go back to the beginning of the result set with the data_seek method.

if (!$user = new LG_User($result))
    print("Failed to create user!<br>");
$result->data_seek(0);
while($row = $result -> fetch_assoc()) {
    $rows[] = $row;
}
var_dump($rows);