How can PHP code be optimized to prevent unnecessary array nesting when loading data from a database?
When loading data from a database in PHP, unnecessary array nesting can be prevented by using the fetch_assoc() method instead of fetch_array(). This method returns an associative array with column names as keys, avoiding the need for numeric indexes and reducing nesting levels. By fetching data directly into an associative array, the code becomes more readable and efficient.
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Query the database
$result = $conn->query("SELECT * FROM table");
// Fetch data into an associative array
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
// Close the database connection
$conn->close();
// Use the data array as needed
foreach ($data as $row) {
echo $row['column_name'];
}