Possible Duplicate:
How to count online users on a website
How do I take off the users that have closed the browser or tab and place them back on when they come back to the page in my online user list? here is my code :
$sql = "SELECT
user_id,
user_name,
user_class,
online
FROM
users
WHERE
online = 1
GROUP BY
user_name ASC ";
$result = mysql_query($sql);
if(!$result)
{
echo 'There are currently no user online.' . mysql_error();
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'There are currently no user online.';
}
else
{
//display category data
while($row = mysql_fetch_assoc($result))
{ $D= $row['online'];
if( ($D) !=1)
{
echo 'There are currently no user online.';
}
else
{
echo'<a href="/index.php?area=profile&userid=' . $row['user_id'] . '" ' . $row['user_class'] . '>' . $row['user_name'] . '</a>, ';}}}}?>
You wouldn’t use a flag in the DB like this.
You should set a relational table that logs the last appearance of the user. Usually a margin of 5 minutes or so.
Basically, every page load you log in a table user_id, datetime
Then every page load where you care to know who is online you check that table where datetime is >= time – 5 minutes.
The tutorial in the comments may be more useful if you have no idea what I mean, but in general the idea is this:
Log when a user interacts with the site. This could be on page load, ajax request, etc, in a relational table. I suggest relational because it allows you to track all behavior and avoids updating the user table unnecessarily.
Then on page load you query that table. You can either do it directly for a count, or join on the user table to report WHO is online. Below is a basic query to get results from the last 5 minutes.
This is just to give a basic idea of the structure. A use case scenario would require a lot more info on your needs, existing code, etc.