Log in

View Full Version : Sql table for users online help



keyboard
09-21-2011, 07:44 AM
Hello everyone,

When a person logs into the member area on my site, their username and the time they logged in, is added to a database called online. From this, I can get a list of everone who is online at the moment. When they log off, their username is deleted from the table. The only problem is if the person dosen't log off before exiting my site, it will look as if they are still online. I would like a way to remove any user who hasn't been active for so many minuts(how do you spell it?) from the table. I'm sorry if I didn't explain it very well. Any help would be great!

djr33
09-21-2011, 03:29 PM
There are two methods:
1. Run a cron job (linux, or similar method on windows, etc) every 5-15 minutes and delete any entries older than X minutes.
2. Skip the cron job and just run that delete query every time anyone loads the page, when you log that individual.

(2) is easier and should be fine:

mysql_query('LOG CURRENT USER');
mysql_query('DELETE FROM `online` WHERE `time`<'.time()-(15*60).';');

That assumes you are using unix timestamps and that you want entries older than 15 minutes to be deleted. In fact, I think 15 minutes is fairly common. You could do something lower (for example, 5 minutes), but that might mean that users just have not refreshed the page for 5 minutes. Of course they will be "online" again the next time they do load a page.

Of course this is a bit excessive because it will run every time any user loads any page, but it does not take many extra resources from the system and will guarantee an accurate table always.


The best way to think of this for static pages is that users are "online" if they have been recently online in the last few minutes-- such as 15. That doesn't mean they are still online, but they have been around recently. The situation would be different for a chatroom, for example, but since there is no accurate way unless they are constantly reloading the page (as in a chatroom) then you can't be certain about this with static pages.

For an example, the forum here works like that. I think it's 15 minutes too.

keyboard
09-21-2011, 11:24 PM
Woudn't I have to put this on everypage to stop the users that are still online from being deleted?


mysql_query('DELETE FROM `online` WHERE `time`<'.time()-(15*60).';');
mysql_query("UPDATE `online`SET `time`= 'time()' WHERE `username`='$username42' ") or die(mysql_error());


would that work?

djr33
09-22-2011, 12:45 AM
Yes, it is best to place this on every page-- otherwise you will just have a list of people who are on one page. Also, it won't matter which order you use the statements because the time between them will never be more than 15 minutes.