Question

I want to check whether a user is online. I've got a status column in my members table. That column logs the last timestamp of the users activity. If the user wont do anything within 5 minutes (meaning he's not active) the user should disappear from the users_online page.

This is how I store the last activity of the user:

$setStatus = mysqli_query($mysqli,"UPDATE members SET status = '".time()."' WHERE id = '".$_SESSION['user_id']."'");

Now on the users_online page, I select the username where the status (the latest timestamp) is the current time, with an interval of 5 minutes. Meaning, if the user latest timestamp is within the 5 mins interval, it should show that users USERNAME. If it has been longer than 5 minutes, he'll be marked as offline.

This is what I've got:

$getUsers = mysqli_query($mysqli,"SELECT username FROM members WHERE status = (NOW() - INTERVAL 5 MINUTE)");
if ( mysqli_num_rows($getUsers) > 0 ) { 
     $row = mysqli_fetch_array($getUsers);
echo $row['username']; 
} else {
 echo "Nobody online";
}

Now the problem is; it keeps saying there is nobody online, even though I've been active with my account.

Am I missing or doing something wrong? Any help would be highly appreciated.

Was it helpful?

Solution 3

$t =time()-5*60;    
$strSql = "SELECT username FROM members WHERE status > ".$t;
echo $strSql;

// run this query into my sql server
$getUsers = mysqli_query($mysqli,$strSql);
if ( mysqli_num_rows($getUsers) > 0 ) { 
    $row = mysqli_fetch_array($getUsers);
    echo $row['username']; 
} else {
    echo "Nobody online";
}

Try to run the query in the MySQL server, then you will be clear about the problem :)

OTHER TIPS

status = (NOW() should be status > (NOW() as you want all within a time period, and not just exactly 5 minutes ago

time() gives the amount of seconds since 1970 and in your sql statement you should say something like

"SELECT username FROM members WHERE status BETWEEN " . time() - (60*5) . " AND " . time() . ")"

Make use of PHP time() function rather than the mysql now() function.

"SELECT username FROM members WHERE status >= '".time()-(60*5)."')"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top