How does using prepared statements in PHP help prevent SQL injection?

Using prepared statements in PHP helps prevent SQL injection by separating SQL code from user input. This means that user input is treated as data rather than executable code, making it impossible for malicious SQL commands to be injected into the query. Prepared statements also automatically sanitize input, reducing the risk of SQL injection attacks.

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