I was making a chat for my website. For that I need to find how many registered users are online. I count the number of sessions and store them in a table. When they logout, their name is removed from that table. Now if they don't click logout and directly close their tab, it does not make them go offline. Their name still exists in table. So to remove them, I found a very complicated algorithm online. It empties that table in every five minutes and then again add the names of the people who are online. But the problem is that while this happens, the chat is interrupted. So I need a way out for this problem
-
1In order to understand this problem a little more, you need to describe your database table structures and how they relate to each other. Ideally, you should have 3 tables. One for user details, one for storing the chat text and one that stores a list of active users. You also need to explain what you mean by 'the chat is interrupted' - do you mean the users loses their chat history or that they are unable to chat whilst your system empties the table (which implies some sort of locking). – James Healey Jun 11 '12 at 15:10
4 Answers
Add a column for "last active." Every time the user performs some action (which may include the browser polling for more messages via AJAX, for example) you update that column to NOW()
. Then your query for finding active users can be something like:
SELECT user.name FROM user
WHERE DATE_ADD(user.last_active, INTERVAL 5 MINUTE) >= NOW();
Deleting old records from the table is fine, but is probably an optional enhancement (depending on site load).

- 158,093
- 24
- 286
- 300
Maybe look into this: destroy session on window close?
Instead of destroying the session you could execute a query that deletes the row.

- 1
- 1

- 1,262
- 2
- 18
- 37
-
The [onunload](http://www.w3schools.com/jsref/event_onunload.asp) event can also be used. – ceving Jun 11 '12 at 15:17
I think there are 2 solution.
1.) Save a timestamp and make a cronjob. The cron check every minute or 2 minuten how old the entries are and delete entries older then 5 minutes for example.
2.) Second way make a funktion which do the same as Point 1 but run the function on every page call. But this is not really efficiant and make a lot of load.

- 26,716
- 22
- 73
- 82
you can easily check the active sessions if you store the sessions in the db table, please check the php manual http://in.php.net/manual/en/function.session-set-save-handler.php

- 166
- 13