Skip to content
PHP Logo

What are best practices for fetching data from a MySQL database in PHP to ensure compatibility with functions expecting arrays?

When fetching data from a MySQL database in PHP, it is important to ensure that the data is formatted as an associative array to maintain compatibility with functions that expect arrays. To achieve this, you can use the mysqli_fetch_assoc() function to fetch rows as associative arrays instead of numeric arrays.

php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Query to fetch data
$result = $mysqli->query("SELECT * FROM table");

// Fetch rows as associative arrays
$data = array();
while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

// Use $data array in functions that expect arrays