How can SQL injection vulnerabilities be prevented when passing user input to a SQL query in PHP?

SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries in PHP. This method ensures that user input is treated as data rather than executable code, thus protecting against malicious SQL injection attacks.

// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=myDB', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();
$results = $stmt->fetchAll();