MySQLi fetch_array - Fetch Row as Array
In PHP, when working with MySQL databases using MySQLi, fetching data efficiently and accurately is crucial. The mysqli_fetch_array() method offers a flexible way to retrieve query result rows as arrays. This tutorial will cover everything you need to know about the mysqli_fetch_array() method, including step-by-step examples, best practices, common mistakes, and interview questions focused on this function.
Prerequisites
- Basic knowledge of PHP and MySQL
- MySQL server setup with accessible database
- PHP installed with MySQLi extension enabled
- A sample database and table to run queries (e.g.,
userstable)
Setup Steps
Before using the mysqli_fetch_array() method you need to establish a connection and run a query. Follow these steps:
- Connect to MySQL Database:
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name'); if ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } - Perform a Query:
$query = "SELECT id, name, email FROM users"; $result = $mysqli->query($query); if (!$result) { die('Query Error: ' . $mysqli->error); } - Fetch Data Using
mysqli_fetch_array(): This is the focus of the tutorial, explained below.
Understanding mysqli_fetch_array()
The mysqli_fetch_array() function fetches one row from a result set as an array. By default, it returns an array with both associative and numeric indices. You can customize its behavior using a second optional parameter called resulttype.
Syntax
mysqli_fetch_array(mysqli_result $result, int $resulttype = MYSQLI_BOTH): array|null|false
$resulttype options:
MYSQLI_ASSOC- Returns associative array with column names as keysMYSQLI_NUM- Returns numeric array with column offsets as keysMYSQLI_BOTH- Returns both associative and numeric arrays (default)
Step-by-Step Examples
1. Fetch Row as Both Numeric and Associative Array (Default)
<?php
$query = "SELECT id, name, email FROM users";
$result = $mysqli->query($query);
if ($result) {
while ($row = mysqli_fetch_array($result)) {
// Access by column name
echo "ID (assoc): " . $row['id'] . "<br>";
// Access by column number
echo "ID (numeric): " . $row[0] . "<br>";
echo "Name: " . $row['name'] . " / " . $row[1] . "<br>";
echo "Email: " . $row['email'] . " / " . $row[2] . "<br><hr>";
}
} else {
echo "Query failed: " . $mysqli->error;
}
?>
2. Fetch Row as Associative Array Only
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "User: " . $row['name'] . " (" . $row['email'] . ")<br>";
}
?>
3. Fetch Row as Numeric Array Only
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo "User: " . $row[1] . " (" . $row[2] . ")<br>";
}
?>
Best Practices
- Close Result Sets: Always free up memory by calling
$result->free();after fetching all rows. - Use
MYSQLI_ASSOCfor clarity: Fetching only associative arrays improves code readability and reduces redundancy. - Validate Query Results: Check that the result set is valid before fetching rows.
- Use Prepared Statements: To prevent SQL injection, prepare your queries before executing, especially when using user input.
Common Mistakes
- Not Checking if Result is Valid:
Not verifying if
$resultis false leads to errors when fetching. - Mismatched Indexing: Using numeric keys for associative arrays or vice versa causes undefined index errors.
- Confusing
fetch_array()withfetch_assoc()orfetch_row(): Know the differences:fetch_assoc()returns associative array onlyfetch_row()returns numeric array onlyfetch_array()can return both or either
- Failing to Free Result Sets: Large result sets can consume excessive memory if not freed.
Interview Questions
Junior-Level Questions
- What does
mysqli_fetch_array()do?
It fetches a row from the result set as an array, either numeric, associative, or both. - What are the possible second parameters for
mysqli_fetch_array()and their purpose?MYSQLI_ASSOC,MYSQLI_NUM,MYSQLI_BOTHcontrol the type of array returned. - How do you access the first column using
mysqli_fetch_array()?
Use$row[0]for numeric or$row['column_name']for associative array. - What is returned by
mysqli_fetch_array()when no rows remain?
It returnsfalse. - Why might you prefer
MYSQLI_ASSOCoverMYSQLI_BOTH?
To avoid duplicate data and improve code clarity.
Mid-Level Questions
- How does
mysqli_fetch_array()differ fromfetch_assoc()andfetch_row()?
It can return both numeric and associative indices; the others return only one type. - Can you fetch multiple rows at once using
mysqli_fetch_array()?
No, you fetch rows one at a time, typically in a loop. - What happens if you do not specify the
resulttypeargument inmysqli_fetch_array()?
It defaults toMYSQLI_BOTH, giving both numeric and associative indices. - Is
mysqli_fetch_array()vulnerable to SQL injections?
No, but unsafe queries executed before fetching can be vulnerable. Use prepared statements. - How would you free memory after fetching rows?
Call$result->free()after finishing fetching.
Senior-Level Questions
- How does using
MYSQLI_NUMaffect performance compared toMYSQLI_BOTH?
Fetching only numeric arrays reduces memory usage and improves performance by avoiding redundant data. - When iterating large datasets, what are implications of using
mysqli_fetch_array()withMYSQLI_BOTH?
It doubles the stored data per row in memory, which increases resource usage. - How can you handle fetching rows efficiently if the query returns millions of results?
Use pagination or streaming, fetch associative arrays only, and free results promptly. - Can
mysqli_fetch_array()be used with prepared statements?
Not directly. You must bind result variables and fetch viamysqli_stmt_fetch(). - Explain a scenario where numeric keys from
mysqli_fetch_array()are preferred over associative keys.
When you only need index-based iteration and want to save memory by avoiding the overhead of associative keys.
Frequently Asked Questions (FAQ)
- Q: What is the default array type returned by
mysqli_fetch_array()? - A: By default, it returns an array containing both numeric and associative keys (
MYSQLI_BOTH). - Q: How do you fetch all rows from a query result?
- A: Use a
whileloop withmysqli_fetch_array()until it returnsfalse. - Q: Can
mysqli_fetch_array()return a multi-dimensional array? - A: No, it returns a one-dimensional array for one row each time it's called.
- Q: What happens if you pass an invalid
resulttypetomysqli_fetch_array()? - A: PHP will default to
MYSQLI_BOTHor may throw a warning depending on error settings. - Q: Is it necessary to free the MySQL result set from
mysqli_query()? - A: It is recommended to free result sets with
$result->free()to free memory, especially with large datasets.
Conclusion
The mysqli_fetch_array() method is a versatile and essential function for retrieving query results in PHP with MySQLi. Understanding how to use its various modesโassociative, numeric, or bothโhelps you write clearer, more efficient code. By following best practices and avoiding common pitfalls, you can handle database results effectively in any PHP project. Whether youโre a beginner preparing for interviews or an experienced developer optimizing performance, mastering mysqli_fetch_array() is invaluable.