What are the potential pitfalls of using mysql_num_rows() to count the number of online users in PHP?
Using mysql_num_rows() to count the number of online users in PHP can be inefficient and potentially inaccurate as it requires a database query for each count request. This can put unnecessary strain on the database server, especially in high-traffic scenarios. To solve this issue, it is recommended to store the online user count in a separate table or cache system that can be easily updated and queried without hitting the database every time.
// Example of storing online user count in a separate table
// Update online user count when a user logs in
// Assuming $userId is the user's ID
$query = "INSERT INTO online_users (user_id) VALUES ($userId)";
$result = mysqli_query($connection, $query);
// Update online user count when a user logs out
// Assuming $userId is the user's ID
$query = "DELETE FROM online_users WHERE user_id = $userId";
$result = mysqli_query($connection, $query);
// Retrieve online user count
$query = "SELECT COUNT(*) AS online_users FROM online_users";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$onlineUsers = $row['online_users'];
echo "Online users: " . $onlineUsers;