Are there any specific best practices for updating online status in PHP applications using MySQL databases?

When updating online status in PHP applications using MySQL databases, it is important to efficiently handle the process to ensure accurate and real-time status updates. One best practice is to use a timestamp field in the database to track the last time a user was active. This timestamp can be updated periodically to reflect the user's online status.

// Update user's online status in MySQL database
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$user_id = 1; // User ID of the user whose online status needs to be updated

// Update the timestamp field for the user to current time
$sql = "UPDATE users SET last_active = NOW() WHERE id = $user_id";

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

$conn->close();