How can prepared statements be utilized in PHP to prevent SQL injection vulnerabilities when executing database queries?

Prepared statements can be utilized in PHP to prevent SQL injection vulnerabilities by separating SQL code from user input. This allows the database to distinguish between the SQL code and the data being passed in, effectively preventing malicious SQL injection attacks.

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