How can prepared statements in PHP help prevent SQL injection vulnerabilities?

Prepared statements in PHP help prevent SQL injection vulnerabilities by separating SQL code from user input. This means that user input is treated as data rather than executable SQL code, significantly reducing the risk of malicious SQL injection attacks.

// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $_POST['username']]);

$results = $stmt->fetchAll();
foreach ($results as $row) {
    // Process the results
}