What are the potential pitfalls of mixing PHP code within a MySQL query in a PHP script?

Mixing PHP code within a MySQL query in a PHP script can lead to security vulnerabilities such as SQL injection attacks. To prevent this, it is recommended to use prepared statements with parameterized queries to sanitize user input and prevent malicious code execution.

// Example of using prepared statements to prevent SQL injection

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL query with a placeholder for user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input to the placeholder
$stmt->bindParam(':username', $username);

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

// Fetch the results
$results = $stmt->fetchAll();