What are the best practices for writing HTML code in PHP to ensure proper display of database results?

When displaying database results in HTML code in PHP, it is important to properly escape the data to prevent any potential security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to achieve this is by using PHP's htmlspecialchars() function to encode any special characters in the data before outputting it in the HTML code.

<?php
// Assume $result is the array of database results
foreach ($result as $row) {
    echo "<div>";
    echo "<p>" . htmlspecialchars($row['column_name']) . "</p>";
    echo "</div>";
}
?>