How can you optimize the code provided to display table data in a more efficient manner?

The code provided currently uses nested loops to display table data, which can be inefficient for large datasets. To optimize the code, we can fetch all the data from the database at once and then loop through the results to display the table rows. This reduces the number of database queries and improves performance.

<?php
// Fetch data from the database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Display table headers
echo "<table>";
echo "<tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>";

// Display table rows
while($row = mysqli_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>" . $row['column1'] . "</td>";
    echo "<td>" . $row['column2'] . "</td>";
    echo "<td>" . $row['column3'] . "</td>";
    echo "</tr>";
}

echo "</table>";
?>