What is the best practice for storing user activity in a MySQL table for online status tracking?

Storing user activity in a MySQL table for online status tracking involves updating the user's last activity timestamp whenever they perform an action on the website. This allows you to track when a user was last active and determine their online status based on a predefined time threshold. To implement this, you can create a MySQL table to store user activity data and update the timestamp field whenever a user interacts with the site.

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Update user's last activity timestamp
$user_id = 123; // Replace with actual user ID
$current_time = time();
$query = "UPDATE user_activity SET last_activity = $current_time WHERE user_id = $user_id";
$mysqli->query($query);

// Check if user is online based on last activity timestamp
$threshold = 300; // 5 minutes threshold for online status
$online_status = ($current_time - $last_activity) <= $threshold ? "Online" : "Offline";
echo "User is currently $online_status";