When executing SELECT queries using MySQLi in PHP, fetch functions are used to retrieve rows from the result set. Each function returns the data in a different structure such as associative arrays, numeric arrays, or objects.
Fetch functions work on the result object returned by mysqli_query() or $conn->query(). Each call retrieves one row and moves the internal pointer forward.
// Connect to MySQL database using MySQLi
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, first_name, last_name, email FROM users";
$result = $conn->query($sql);
// Fetch rows as an associative array
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: ".$row["id"]." Name: ".$row["first_name"]." ".$row["last_name"]." Email: ".$row["email"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
The script connects to the database, runs a SELECT query, and fetches each row using mysqli_fetch_assoc(). Column values are accessed by their names.
Try switching between different fetch functions and observe how the returned data structure changes when using arrays versus objects.
num_rows before fetching