Simple MySQL / PHP Hit Counter
Santomieri Systems
http://www.santsys.com
joshs@santsys.com
Description:
This is a simple hit counter that is indexed via the specified page. If the page specified is not currently in the counter table, it adds it.
It also keeps track of the last IP address so as to limit the number of hits generated by a single source. (all of the functionality is easily modified)
Function to display / update / create the counter on the page:
function HitCounter($page = "")
{
$hits = 0;
// select the code for the page
$sql = "SELECT ID, HITS, LAST_IP FROM counter WHERE PAGE = \"".$page."\"";
$result = mysql_query($sql) or die("Could not execute sql!
".$sql."
".mysql_error());
if(mysql_num_rows($result) > 0)
{
$data = mysql_fetch_assoc($result);
if($data["LAST_IP"] == $_SERVER['REMOTE_ADDR'])
{
$hits = (int)$data["HITS"];
}
else
{
$hits = (int)$data["HITS"] + 1;
$sql = "UPDATE counter SET LAST_IP = \"".$_SERVER['REMOTE_ADDR']."\", HITS = ".$hits." WHERE PAGE = \"".$page."\"";
mysql_query($sql) or die("Could not execute sql!
".$sql."
".mysql_error());
}
}
else
{
// add the page to the list of counters if it does not already exhist
$sql = "INSERT INTO counter (HITS, LAST_IP, PAGE) VALUES (1, \"".$_SERVER['REMOTE_ADDR']."\", \"".$page."\")";
mysql_query($sql) or die("Could not execute sql!
".$sql."
".mysql_error());
$hits = 1;
}
return $hits;
}
Example of inpage code:
You are visitor number .
OR
You are visitor number .
SQL Script to create the MySQL database:
CREATE TABLE `counter` (
`ID` int(11) NOT NULL auto_increment,
`HITS` bigint(20) NOT NULL default '0',
`LAST_IP` varchar(50) NOT NULL default '0.0.0.0',
`PAGE` varchar(200) NOT NULL default '',
`LAST_UPDATE` timestamp(14) NOT NULL,
PRIMARY KEY (`ID`)
)
Here is the code that can be used to manage the counters (it's kind of long, but just cut and paste):
Currently Counters | ||||||
ID | Date / Time | Hits | Last IP | Page | Reset | Delete | No Records To Display |
">Reset | "> |