How can the SELECT query be optimized in the login function to avoid redundancy and improve performance?

The SELECT query in the login function can be optimized by selecting only the necessary columns instead of using SELECT *. This can help avoid redundancy and improve performance by reducing the amount of data retrieved from the database. Additionally, using prepared statements can help prevent SQL injection attacks.

// Optimized SELECT query in the login function
$stmt = $pdo->prepare("SELECT user_id, username, password FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch();

// Check if the user exists and verify password
if ($user && password_verify($password, $user['password'])) {
    // Login successful
    $_SESSION['user_id'] = $user['user_id'];
    $_SESSION['username'] = $user['username'];
    return true;
} else {
    // Login failed
    return false;
}