What best practices should be followed when using PHP to loop through database results and output them in HTML tables?

When looping through database results and outputting them in HTML tables using PHP, it is important to follow best practices to ensure clean and efficient code. One common approach is to use a while loop to fetch each row from the database result set and then output the data within HTML table rows. It is also recommended to sanitize the data to prevent SQL injection attacks and format the output for better readability.

<?php
// Assume $result is the database result set

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>" . htmlspecialchars($row['name']) . "</td>";
    echo "<td>" . htmlspecialchars($row['email']) . "</td>";
    echo "</tr>";
}

echo "</table>";
?>