How can SQL injection vulnerabilities be prevented when executing SQL queries in PHP?

SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries in PHP. This approach separates the SQL query logic from the user input, making it impossible for malicious input to alter the query structure.

// Using prepared statements to prevent SQL injection in PHP
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();