How can prepared statements in PHP help prevent SQL injection attacks in the context of user authentication?

Prepared statements in PHP help prevent SQL injection attacks by separating SQL code from user input. This means that user input is treated as data rather than executable code, reducing the risk of malicious SQL injection. By using prepared statements, the SQL query is precompiled and then the user input is bound to placeholders in the query, ensuring that the input is properly escaped and sanitized.

// Using prepared statements to prevent SQL injection in user authentication

// Assuming $username and $password are user inputs
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();

// Check if user exists and password is correct
if($stmt->rowCount() > 0){
    // User authentication successful
} else {
    // User authentication failed
}