PHP MySQL mysqli_fetch_row function
The mysqli_fetch_row()
function in PHP retrieves a result row from a MySQLi result set as a numeric array. This function is part of the MySQLi extension and is used in procedural style to fetch data from a query result.
Syntax
mysqli_fetch_row(result)
Parameters
- result: The
mysqli_result
object returned bymysqli_query()
when executing aSELECT
query. This object represents the result set from the query.
Return Values
- On success: Returns a numeric array where each element corresponds to a column value in the row. The indices of the array start from 0, corresponding to the column positions.
- On failure: Returns
null
when there are no more rows to fetch (i.e., when all rows have been retrieved).
Example Usage
Here’s a step-by-step example demonstrating how to use mysqli_fetch_row()
:
1. Establish a Database Connection
<?php
// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
2. Execute a SELECT
Query
// Prepare and execute a SELECT query
$sql = "SELECT username, email FROM users";
$result = mysqli_query($conn, $sql);
3. Fetch and Display Rows
if ($result) {
// Fetch rows one by one
while ($row = mysqli_fetch_row($result)) {
// Access data using column indices
echo "Username: " . $row[0] . " - Email: " . $row[1] . "<br>";
}
// Free the result set
mysqli_free_result($result);
} else {
echo "Error: " . mysqli_error($conn);
}
4. Close the Database Connection
// Close the connection
mysqli_close($conn);
?>
How It Works
Fetching Rows: Each call to
mysqli_fetch_row()
retrieves the next row from the result set. It returns the row as a numeric array, with column values accessed using numeric indices.Array Indices: The array indices correspond to the positions of the columns in the result set, starting from 0. For example, the first column value is accessed with
$row[0]
, the second with$row[1]
, and so on.End of Result Set: When there are no more rows to fetch,
mysqli_fetch_row()
returnsnull
.Freeing Result Set: After processing the result set, use
mysqli_free_result()
to free the memory associated with it.
Notes
- Numeric Indexes:
mysqli_fetch_row()
is useful when you want to access data by column index rather than by column name. - Performance: Fetching rows as numeric arrays can be slightly faster than fetching them as associative arrays because there is no overhead of creating associative keys.