PHP Users Online with Mysql

Using PHP and Mysql you can keep track of the users online your website and display it on your page.

First thing ,we need a table in our Mysql database for the users online. So let’s make a table in our database.

[code lang=”sql”]
mysql_query(“CREATE TABLE online(
id INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
ip_address VARCHAR(25) NOT NULL,
timestamp VARCHAR(25) NOT NULL)”) or die(mysql_error());
[/code]

Now that we have the table, we need to update the users online on every page. That way it is most accurate and up to date with who is currently online. We will set a time offset so that we include all users online within the past 5 minutes.

[code lang=”php”]
0){
mysql_query(“UPDATE online SET timestamp = ‘”.time().”‘ WHERE ip_address = ‘$ip’) or die(mysql_error());
} else {
mysql_query(“INSERT INTO online (ip_address,timestamp) VALUES (‘$ip’,'”.time().”‘)”) or die(mysql_error());
}
$delete = mysql_query(“DELETE FROM online WHERE timestamp < '$time_offset'") or die(mysql_error()); ?>
[/code]

Now every time someone goes on a page with this code, mysql will check to see if the user is in the system, and if so update their current timestamp, otherwise create a row for them in the table. It will also erase any rows with old timestamps. This will keep the table clean and updated.

Now we count the users online and show it on the page.

[code lang=”php”]
‘$time_offset'”);
$online = mysql_num_rows($sql);

return ‘There are ‘.$online.’ user(s) currently online. ‘;
}
?>
[/code]

Filed under: TutorialsTagged with: , ,

4 Comments

  1. Thanks man, big halp!

  2. I completely agree with the above comment, the web is without a doubtgrowing into the most important medium of communication across the world and its due to sites like this that ideas are spreading so quickly arround.

  3. Many thanks for writing this, I thought it was very useful, and it answered the vast majority of the concerns I had.

  4. Hmmm…great to know, there were certainly a couple of things in which I had not thought of before.


Add a Comment

Your email address will not be published. Required fields are marked *

Comment *
Name *
Email *
Website