How can the code provided in the forum thread be improved to prevent login problems?

The code provided in the forum thread is vulnerable to SQL injection attacks, which can lead to login problems and compromise user data. To prevent this, the code should use prepared statements with parameterized queries to sanitize user input and prevent malicious SQL injection.

// Improved code using prepared statements to prevent SQL injection

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

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

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

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

// Check if user exists
if ($stmt->rowCount() > 0) {
    // User authenticated successfully
    // Redirect to dashboard or home page
    header("Location: dashboard.php");
    exit();
} else {
    // Invalid credentials
    echo "Invalid username or password";
}