View Full Version : users online script trouble

05-13-2008, 03:00 AM
Need some help with my script.

$online['time'] = time();
if (isset($_SESSION['db_logged_in'])) {
$update = mysql_query("UPDATE users SET last_login = '".$online['time']."', logged = '1' WHERE username = '".$session['username']."'") or die (mysql_error());

$last = mysql_query("SELECT * FROM users WHERE username = '".$session['username']."'") or die (mysql_error());
$last2 = mysql_fetch_array($last);
if ($last2['last_logged'] > $online['time'] - 30) {
$q2 = mysql_query("UPDATE users SET logged = '0' WHERE username = '".$session['username']."'") or die (mysql_error());

What it does is check for the session, and if it is there than it makes the database queries to make the user "appear online". However, my problem is with setting the "logged" value to 0 when the user leaves the website. The script is suppose to check that if the user hasn't made any activity for 30 seconds, then the "logged" value is set to 0. However, it does not do this, and "logged" is still set to 1. I'm not sure where the error lies. Assistance is appreciated.

05-13-2008, 03:24 AM
Why not instead of having a database where it sets you logged in or out use $_SESSION variables as they die when you close the browser secondly right put the last logined date and update every time they reload the page and then do a simple check like

if ($row['last_logined']+300 < time())
// Offline

// Online

how it'll work is if the user has been active it'll show him as online as the time will be within the last 5 minutes but he hasn't been logined it won't it's untested anyhow..

or alternatively use the same update the last_login everytime they reload a page and use this to get the online users of course if they logout set the last_login to time()-300 or 0

$time = time();
$sql = "SELECT * FROM users WHERE last_login<'{$time}'"
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query))
echo "{$row['username']}<br />\n";


05-14-2008, 12:31 AM
The reason why I used a database is because my users info is in the database. I want to display the list of online users on the site, but I also want to color code the admins and mods. So the necessary data would have to be pulled out of the database.

I understand where you are going with the $_SESSION variables. I use them for my site, but are they the best way to display a list of online users?

Would something like this work?

if ($row['last_login'] + 300 < time()) {
else {
// update database with last login time