How can prepared statements help prevent SQL injections in PHP when working with databases?

Prepared statements in PHP help prevent SQL injections by separating SQL code from user input. This means that user input is treated as data rather than executable code, making it impossible for an attacker to inject malicious SQL queries.

// Using prepared statements to prevent SQL injections
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $username]);
$results = $stmt->fetchAll();