What are the best practices for displaying query results in HTML tables using PHP?

When displaying query results in HTML tables using PHP, it is important to properly structure the table with appropriate headers and rows to present the data clearly to the user. It is also crucial to sanitize the data to prevent any potential security vulnerabilities. Utilizing PHP functions like mysqli_fetch_assoc() to fetch data from the database and looping through the results to populate the table is a common practice.

<?php
// Assume $result is the result of a database query
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>";
?>