How can the use of fetch-all function in MySQLi improve the code efficiency?

Using the fetch-all function in MySQLi can improve code efficiency by reducing the number of database queries needed to retrieve data. Instead of fetching rows one by one, fetch-all retrieves all rows at once, reducing the overhead of multiple queries and improving performance. This can be particularly beneficial when dealing with large result sets or when needing to process data in bulk.

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

// Query to fetch all rows at once
$result = $mysqli->query("SELECT * FROM table");
$rows = $result->fetch_all(MYSQLI_ASSOC);

// Loop through the results
foreach($rows as $row) {
    // Process each row
    echo $row['column_name'] . "<br>";
}

// Close the database connection
$mysqli->close();