How can the code be improved to correctly update the user's online status in PHP?

The issue can be resolved by updating the user's online status in the database when they log in or log out. This can be achieved by setting a flag in the database indicating whether the user is currently online or not.

// Update user's online status when logging in
$user_id = $_SESSION['user_id'];
$sql = "UPDATE users SET online_status = 1 WHERE id = $user_id";
$result = mysqli_query($conn, $sql);

// Update user's online status when logging out
$user_id = $_SESSION['user_id'];
$sql = "UPDATE users SET online_status = 0 WHERE id = $user_id";
$result = mysqli_query($conn, $sql);