Reputation: 397
I can't design mysql tables for "is user online" feature. Googled but can't find concrete solutions. Any help would be appreciated. Thank you.
Upvotes: 1
Views: 1440
Reputation: 5096
You can build on something like this:
Create a tblOnline table with the following fields
id int not null auto_increment primary key
colSession text
colStamp int
When someone login you create a session variable for them:
session_start();
$_SESSION['online'] = md5(uniqid(rand(), true)); // Create a unique string
Store the unique session in tblOnline:
$stamp = time();
mysql_query('INSERT INTO tblOnline (colSession,colStamp) VALUES ('.$_SESSION['online'].','.$stamp.')');
When they do something (like, the page reloads) update the colStamp with the current timestamp:
$now = time();
mysql_query('UPDATE tblOnline SET colStamp = '.$now.' WHERE colSession = '.$_SESSION['online'].'');
To get all the online users do something like:
$timecheck = time()-(60*5); // 5 minutes back
$rs = mysql_query('SELECT * FROM tblOnline WHERE Stamp > '.$timecheck.'');
$num = mysql_num_rows($rs);
echo "There are: ".$num." users online right now!";
Clean up old session data from the database from time to time (matching on colStamp of course):
$timeclean = time()-(60*60); // One hour back
mysql_query('DELETE FROM tblOnline WHERE Stamp < '.$timeclean.'');
Upvotes: 1
Reputation: 30741
Store the Session in the DB, store the user_id as extra field in the session table.
query session table for open sessions
But be aware that sessions are not a 100% representation of users which are really on the site. (session timeouts).
Upvotes: 3
Reputation: 1105
One possibility would be to save the last action of every user in your database (as timestamp) and say "every user who performed some action in the last 2 minutes is online".
If you updated this with ajax for example, you will be able to track who closed the page and who not.
Upvotes: 4