What are the best practices for generating dynamic HTML content with PHP while avoiding common pitfalls like displaying incorrect data?

When generating dynamic HTML content with PHP, it is essential to properly sanitize and validate user input to prevent injection attacks and ensure that only valid data is displayed. It is also crucial to use prepared statements when interacting with databases to prevent SQL injection vulnerabilities. Additionally, utilizing functions like htmlspecialchars() can help escape special characters and prevent cross-site scripting attacks.

// Example of sanitizing user input and using prepared statements
$userInput = $_POST['user_input'];
$cleanInput = filter_var($userInput, FILTER_SANITIZE_STRING);

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $cleanInput);
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "<p>" . htmlspecialchars($row['username']) . "</p>";
}