How can SQL injection vulnerabilities be prevented in PHP code, especially when handling user input for login systems?

SQL injection vulnerabilities can be prevented in PHP code by using prepared statements with parameterized queries. This approach ensures that user input is treated as data rather than executable SQL code, thus preventing malicious SQL injection attacks.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');

// Bind parameters to placeholders
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);

// Execute the prepared statement
$stmt->execute();

// Check if the user exists
$user = $stmt->fetch();
if ($user) {
    // User is authenticated
} else {
    // Invalid credentials
}