Loop through MySQLi results
suggest changeA while loop can walk a result. The fetch returns no row at the end, so the loop stops. Since PHP 8.1 that return value is null. Older versions returned false. Both are falsy, so the while condition is the same. These examples work with
- mysqli_fetch_assoc - Associative array with column names as keys
- mysqli_fetch_object -
stdClassobject with column names as properties - mysqli_fetch_array - Associative AND Numeric array (can use arguments to get one or the other)
- mysqli_fetch_row - Numeric array
Object oriented style
while($row = $result->fetch_assoc()) {
var_dump($row);
}
Procedural style
while($row = mysqli_fetch_assoc($result)) {
var_dump($row);
}
To get exact information from results, we can use:
while ($row = $result->fetch_assoc()) {
echo 'Name and surname: '.$row['name'].' '.$row['surname'].'<br>';
echo 'Age: '.$row['age'].'<br>'; // Prints info from 'age' column
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents