How can SQL injection be prevented in PHP login systems?

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

// Using prepared statements to prevent SQL injection in PHP login system

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

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

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

// Execute the query
$stmt->execute();

// Fetch the results
$user = $stmt->fetch();

// Check if a user was found
if ($user) {
    // User authenticated successfully
    echo 'Login successful';
} else {
    // Invalid credentials
    echo 'Invalid username or password';
}