What best practices should be followed when displaying database query results in a PHP application to ensure accurate data representation?

When displaying database query results in a PHP application, it is important to properly handle and format the data to ensure accurate representation. This includes sanitizing user input to prevent SQL injection attacks, validating and formatting the data before displaying it to the user, and handling errors gracefully to provide a better user experience.

// Example code snippet for displaying database query results in a PHP application

// Assuming $result is the database query result
if ($result) {
    echo "<table>";
    foreach ($result as $row) {
        echo "<tr>";
        foreach ($row as $key => $value) {
            echo "<td>" . htmlspecialchars($value) . "</td>"; // Sanitize user input
        }
        echo "</tr>";
    }
    echo "</table>";
} else {
    echo "No results found.";
}