What best practices should be followed when outputting SQL query results in HTML using PHP?

When outputting SQL query results in HTML using PHP, it is important to properly handle the data to prevent any security vulnerabilities such as SQL injection attacks. One best practice is to use prepared statements to bind parameters securely. Additionally, it is recommended to sanitize the output data to prevent cross-site scripting (XSS) attacks. Finally, consider using a templating system like Twig to separate the presentation layer from the logic.

<?php
// Assuming $conn is the database connection and $query is the SQL query
$stmt = $conn->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo "<table>";
echo "<tr><th>ID</th><th>Name</th></tr>";
foreach ($results as $row) {
    echo "<tr><td>" . htmlspecialchars($row['id']) . "</td><td>" . htmlspecialchars($row['name']) . "</td></tr>";
}
echo "</table>";
?>