STATISTICS

If you are in a mood to learn how a "Users Online Counter" works, then you are at the correct place.

Here, I've used ip address to determine unique visitors. If you wan't to use this counter for any organisations where the employees used same network(having same ip address) then use sessions or cookies instead.

THE DATABASE

Whenever, a new user hits the page, it's ip address gets stored in the table "counter" & simultaneously the "inactive" ip addresses get deleted. Let's have a look on the table structure...

database sql

INDEX.PHP
<?php
$conn=mysql_connect("","","") or die("could not connect");
$db=mysql_select_db("",$conn) or die("could not select database");
$ip = $_SERVER['REMOTE_ADDR'];
$tstamp=time();
$query="SELECT * FROM counter";
$result=mysql_query($query);
$num=mysql_numrows($result);

if($num==0)
{
 
 mysql_query("INSERT INTO counter(tstamp,ip) VALUES('$tstamp','$ip')")or die("s");
 
}
else
{ 
 $i=0; 

 while ($i < $num) {
 
 if($ip!=mysql_result($result,$i,"ip"))
 {
 
 mysql_query("INSERT INTO counter(tstamp,ip) VALUES('$tstamp','$ip')");
 
 }
 $i++;
 
 }
}

$tout=120;
mysql_query("DELETE FROM counter WHERE tstamp<($tstamp-$tout)");
echo mysql_num_rows(mysql_query("SELECT * FROM counter"));  
?>


Leave a Comment  
Download Code(45)





All rights reserved, the content is copyrighted to the author.

RELATED POST