How can SQL Injection vulnerabilities be mitigated in PHP login scripts?

SQL Injection vulnerabilities in PHP login scripts can be mitigated by using prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps prevent malicious SQL code from being injected into the query and executed by the database.

// 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();

if ($user) {
    // Login successful
    session_start();
    $_SESSION['user_id'] = $user['id'];
    echo 'Login successful';
} else {
    // Login failed
    echo 'Invalid username or password';
}