What are the potential pitfalls of mixing SQL queries with HTML code in PHP scripts, and how can this be avoided?

Mixing SQL queries with HTML code in PHP scripts can lead to security vulnerabilities such as SQL injection attacks. To avoid this, it is recommended to separate the SQL queries from the HTML code by using prepared statements and parameterized queries. This helps to sanitize user input and prevent malicious code from being executed.

<?php
// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare SQL statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind parameters
$stmt->bindParam(':username', $_POST['username']);

// Execute SQL query
$stmt->execute();

// Fetch results
while ($row = $stmt->fetch()) {
    // Output HTML code
    echo "<p>{$row['username']}</p>";
}
?>