How can PHP code be optimized to prevent SQL injection attacks in a login form?

To prevent SQL injection attacks in a login form, PHP code can be optimized by using prepared statements with parameterized queries. This technique allows the database engine to distinguish between SQL code and user input, effectively preventing malicious SQL injection attempts.

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

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

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

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

// Check if the login was successful
if($stmt->rowCount() > 0) {
    // User authenticated
    echo "Login successful";
} else {
    // Invalid credentials
    echo "Invalid username or password";
}