In what situations should the use of mysqli_fetch_array() be preferred over other methods in PHP?
When you need to fetch rows from a MySQL database result set and access the data both by column name and by index, mysqli_fetch_array() should be preferred over other methods. This function returns an array that contains both associative and numeric indices, allowing for flexible data access.
// Connect to the database
$conn = mysqli_connect("localhost", "username", "password", "database");
// Execute a query
$result = mysqli_query($conn, "SELECT * FROM table");
// Fetch rows using mysqli_fetch_array()
while ($row = mysqli_fetch_array($result)) {
// Access data by column name
echo $row['column_name'];
// Access data by index
echo $row[0];
}
Related Questions
- How can PHP be used to calculate the sum of values in an array?
- What are some common methods for calculating the time until a specific point in the future using PHP timestamps?
- In what situations would it be more efficient to use the STR_TO_DATE function directly in SQL queries for date conversions instead of handling them in PHP code?