Simple “Who is online” in PHP and MySQL
29 Dec 2010Hi guys,
If you want a simple “Who is Online” for your website, just read the post. It’s really quite simple.
Please note, I’ve used a PHP/MySQL wrapper for handling my connections to the database. (http://www.ricocheting.com/code/php/mysql-database-class-wrapper-v3)
I created a class to handle the database-specific code:
<?php
class People {
function exists($ip) {
$db = Database::obtain();
$sql = "SELECT 1 FROM " . tbl_people . " WHERE ip = " . ip2long($ip);
$row = $db->query_first($sql);
if (!empty($row)) {
return true;
}
else {
return false;
}
}
function online() {
$db = Database::obtain();
$sql = "SELECT COUNT(*) as counted FROM " . tbl_people;
$row = $db->query_first($sql);
return $row['counted'];
}
function insert($ip) {
$db = Database::obtain();
$data['ip'] = ip2long($ip);
$data['time'] = "NOW()";
$pid = $db->insert(tbl_people, $data);
return $pid;
}
function update($ip) {
$db = Database::obtain();
$data['time'] = "NOW()";
$db->update(tbl_people, $data, "ip=" . ip2long($ip));
}
function truncate() {
$db = Database::obtain();
$sql = "DELETE FROM " . tbl_people . " WHERE time < SUBTIME(NOW(),'0 0:10:0')";
$db->query($sql);
}
}
?>
The flow goes like this:
- Someone visits your website, so we check to see if their IP address already exists in the database
- If it doesn’t we add their IP address
- If it does, we update the timestamp associated with that IP address
- Then we run truncate the table of old timestamps. (10minutes)
- Finally, we count how many rows are in the table, and output that as the amount of people on the website.
Put that all together:
<?php
require_once('class_people.php');
$people = new People;
$ip = $_SERVER['REMOTE_ADDR'];
if (!$people->exists($ip)) {
$people->insert($ip);
}
else {
$people->update($ip);
}
$people->truncate();
echo $people->online();
?>
I hope that covers it!
The tutorial should be simple enough for you to use basic PHP mysql connection code, PDO etc. If you have a problem, don’t hesitate to ask.
Tags: PHP, who's online