How can prepared statements improve the security of PHP code?

Using prepared statements can improve the security of PHP code by preventing SQL injection attacks. Prepared statements separate the SQL query from the user input, allowing the database to distinguish between code and data. This helps to prevent malicious SQL code from being injected into the query.

// Using prepared statements to prevent SQL injection
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();