Loop through MySQLi results
suggest changePHP makes it easy to get data from your results and loop over it using a while
statement. When it fails to get the next row, it returns false
, and your loop ends. These examples work with
- mysqli_fetch_assoc - Associative array with column names as keys
- mysqli_fetch_object -
stdClass
object with column names as variables - 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