How can PHP be used to format MySQL query results in an HTML table?

When retrieving data from a MySQL database using PHP, it is common to display the results in an HTML table for better readability. To achieve this, you can iterate through the query results and format them into table rows and cells within a loop. By using PHP to generate the HTML table structure dynamically, you can easily display the MySQL query results in a user-friendly format.

<?php
// Assuming $result is the variable holding the MySQL query results

echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";

while($row = mysqli_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td>" . $row['name'] . "</td>";
    echo "<td>" . $row['email'] . "</td>";
    echo "</tr>";
}

echo "</table>";
?>