Users Online
Category: PHPReviewed by: armed rebel
Reviewed on: Jul 05 2006
» Discuss this topic ( Posts)
So now we have added and updated all the users that browse your site, and we're ready to display them. You can essentially change how it displays to how you want, but to simplify things I'll just create a line for the counts and show the users "list-style".
$now=time(); $cut_off = $now - 300; $members_sql = "SELECT DISTINCT user_id FROM users_online WHERE guest='0' AND last_active >= '$cut_off'"; $members_query = mysql_query($members_sql); $members = mysql_num_rows($members_query); $guests = mysql_num_rows(mysql_query("SELECT DISTINCT sess_id FROM users_online WHERE guest='1' AND last_active >= '$cut_off'")); <b>Users Online</b> Members Online: $members -- Guests Online: $guests while($user = mysql_fetch_array($members_query)) { $user = mysql_fetch_array(mysql_query("SELECT username FROM users WHERE user_id='$user[user_id]'")); echo "$user[username]<br />"; }
There isn't much else to say here as the script above speaks for itself. Again, the time() function gets the seconds since the Unix Epoch, then for the $cut_off variable, we simply subtract 5 minutes (5 * 60 = 300) from that count. You can change this to what you want. Secondly, we need to only select the rows that have different user_ids stored (if we didn't, then it's possible to get one user showing up multiple times on the list), so we use the DISTINCT MySQL function.
Note: When looking at the above script, you can see that there are two "= ?>"s. This is a quick, easy way to display PHP variables without having to create a new PHP section and it gives a cleaner code look.

