How can the error in the code snippet be corrected to ensure the last login date is updated correctly?

The issue in the code snippet is that the last login date is being updated with the current date and time every time the user logs in, instead of updating it only when the user logs in successfully. To solve this issue, the last login date should be updated only if the login is successful. This can be achieved by moving the update query inside the if statement that checks if the login is successful.

// Check if the login is successful
if ($login_successful) {
    // Update the last login date in the database
    $last_login_date = date("Y-m-d H:i:s");
    $update_query = "UPDATE users SET last_login = '$last_login_date' WHERE username = '$username'";
    // Execute the update query
    $result = mysqli_query($connection, $update_query);
}