This function allows you to fetch a result row as an associative array, a numeric array, or both. This article will delve into the details of mysqli_fetch_array(), providing examples and use cases to illustrate its utility.
Understanding mysqli_fetch_array()
The mysqli_fetch_array() function fetches a result row as an associative array, a numeric array, or both. Its basic syntax is:
mysqli_fetch_array(result, array_type);
result: The result resource that is being evaluated. This result comes from a call to mysqli_query(), mysqli_store_result(), or mysqli_use_result().
array_type: This optional parameter specifies what type of array to return. It can be one of the following values:
MYSQLI_ASSOC (fetches associative array)
MYSQLI_NUM (fetches numeric array)
MYSQLI_BOTH (default, fetches both associative and numeric array)
Basic Usage of mysqli_fetch_array()
Let’s start with a simple example. Consider a table named users with the following structure:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
age INT NOT NULL
);
Example 1: Fetching Data as an Associative Array
In this example, we fetch data from the users table and print it as an associative array.
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to select all users
$sql = "SELECT id, username, email, age FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "ID: " . $row["id"] . " - Username: " . $row["username"] . " - Email: " . $row["email"] . " - Age: " . $row["age"] . "
";
}
} else {
echo "0 results";
}
$conn->close();
?>
In this example, we use MYSQLI_ASSOC to fetch each row as an associative array. The keys of the array correspond to the column names of the fetched data.
Example 2: Fetching Data as a Numeric Array
In this example, we fetch data from the users table and print it as a numeric array.
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to select all users
$sql = "SELECT id, username, email, age FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo "ID: " . $row[0] . " - Username: " . $row[1] . " - Email: " . $row[2] . " - Age: " . $row[3] . "
";
}
} else {
echo "0 results";
}
$conn->close();
?>
In this example, we use MYSQLI_NUM to fetch each row as a numeric array. The keys of the array are numeric indices, starting from 0.
Example 3: Fetching Data as Both Associative and Numeric Arrays
In this example, we fetch data from the users table and print it as both an associative and numeric array.
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to select all users
$sql = "SELECT id, username, email, age FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo "ID: " . $row["id"] . " - Username: " . $row["username"] . " - Email: " . $row["email"] . " - Age: " . $row["age"] . "
";
echo "ID: " . $row[0] . " - Username: " . $row[1] . " - Email: " . $row[2] . " - Age: " . $row[3] . "
";
}
} else {
echo "0 results";
}
$conn->close();
?>
In this example, we use MYSQLI_BOTH to fetch each row as both an associative and numeric array. This provides the flexibility to access data using either the column names or numeric indices.
Use Cases for mysqli_fetch_array()=
Use Case 1: Displaying Data in an HTML Table
One common use case for mysqli_fetch_array() is to display data in an HTML table. This is especially useful for creating dynamic web pages that display database content.
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to select all users
$sql = "SELECT id, username, email, age FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo " ID Username Email Age ";
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "" . $row["id"] . " " . $row["username"] . " " . $row["email"] . " " . $row["age"] . " ";
}
echo "
";
} else {
echo "0 results";
}
$conn->close();
?>
This code retrieves data from the users table and displays it in an HTML table. Each row of the result set is fetched using mysqli_fetch_array() and printed inside the table rows.
Use Case 2: Processing Data for Further Operations
Sometimes, you may need to fetch data from a database, process it, and then perform additional operations based on the retrieved data. Here’s an example where we calculate the average age of users:
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to select all users
$sql = "SELECT age FROM users";
$result = $conn->query($sql);
$total_age = 0;
$count = 0;
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$total_age += $row[0];
$count++;
}
$average_age = $total_age / $count;
echo "The average age of users is: " . $average_age;
} else {
echo "0 results";
}
$conn->close();
?>
In this example, we fetch the age column from the users table, sum the ages, and calculate the average age.
Use Case 3: Fetching Data for JSON API Responses
When building APIs, it’s common to fetch data from a database and return it as a JSON response. Here’s an example of how to do this using mysqli_fetch_array():
connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to select all users
$sql = "SELECT id, username, email, age FROM users";
$result = $conn->query($sql);
$users = array();
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$users[] = $row;
}
echo json_encode($users);
} else {
echo json_encode(array());
}
$conn->close();
?>
This code fetches data from the users table, stores it in an array, and returns it as a JSON response. This is particularly useful for building RESTful APIs.