What are best practices for handling user logout actions to update online status in a PHP application?

When a user logs out of a PHP application, it is important to update their online status to reflect that they are no longer active. This can be achieved by setting a flag in the database or updating a timestamp indicating their last activity. By updating the user's online status upon logout, the application can accurately display who is currently active.

// Assuming you have a users table with a column 'online_status'

// Update the user's online status to offline upon logout
$user_id = $_SESSION['user_id']; // Assuming you are using sessions for user authentication

// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check for connection errors
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Update the user's online status to offline
$sql = "UPDATE users SET online_status = 'offline' WHERE id = $user_id";

if ($conn->query($sql) === TRUE) {
    echo "User online status updated successfully";
} else {
    echo "Error updating online status: " . $conn->error;
}

// Close the database connection
$conn->close();