How can PHP developers prevent SQL injection attacks when handling user authentication and data comparisons?

To prevent SQL injection attacks when handling user authentication and data comparisons in PHP, developers should use prepared statements with parameterized queries. This method separates SQL code from user input, making it impossible for malicious input to alter the SQL query structure.

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