What common mistakes can occur when handling form data in PHP, as seen in the provided code snippet?

One common mistake when handling form data in PHP is not properly sanitizing user input, leaving the application vulnerable to SQL injection attacks. To solve this issue, always sanitize and validate user input before using it in SQL queries or displaying it on the page.

// Sanitize and validate user input before using it
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();

// Display appropriate error message if login fails
if($stmt->rowCount() > 0){
    echo "Login successful!";
} else {
    echo "Invalid username or password.";
}