Skip to content
PHP Logo

How can PHP be used to count and display online users from a database while ignoring offline users?

To count and display online users from a database while ignoring offline users, you can create a column in the database to store the last activity time of each user. Then, you can query the database to select users whose last activity time is within a certain threshold (e.g., within the last 5 minutes) to consider them as online users. Finally, you can count and display the number of online users based on the query results.

php
// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Define the threshold time for considering users as online (e.g., within the last 5 minutes)
$thresholdTime = time() - (5 * 60);

// Query to select online users based on last activity time
$query = "SELECT COUNT(*) as online_users FROM users WHERE last_activity_time > $thresholdTime";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);

// Display the number of online users
echo "Online Users: " . $row['online_users'];

// Close the database connection
mysqli_close($connection);