PHP - Basic page hits counter

From Global Programming Syntax

Jump to: navigation, search

One thing a website needs is a visitor/hits counter to see how popular your site is. This once upon time was done in Javascript, CGI script and Flash but today we now have even more languages such as PHP and Ajax which can deliver better and more accurate results. The counter below is just a basic one which when inserted into a page, will save any visits into a mysql database and will return the number of visits when the getstats() function is called. So to setup the database, run the following script.

<?
$dbhost='localhost'; //database host (usually localhost)
$accountname='root'; //database username.
$password=''; //database password
$database='my_database'; //database name - not table
 
//configure the above variables.
 
 
$linkID = @mysql_connect($dbhost,$accountname,$password)
or die("Could not connect to MySQL server");
@mysql_select_db($database) or die("Could not select database");
 
mysql_query('CREATE TABLE `'.$database.'`.`stats` (`url` TEXT NOT NULL, `visits` TEXT NOT NULL) ENGINE = MyISAM')
or die(mysql_error());
echo "Table named 'stats' has been created successfully.";
?>

After you have configured and executed/ran the above script, you then may delete the php file containing that script and proceed with the instructions below. Next place the below script at the top of the document you wish to use the stats counter in.

<?
$dbhost='localhost'; //database host (usually localhost)
$accountname='root'; //database username.
$password=''; //database password
$database='my_database'; //database name - not table
 
//configure the above variables.
 
 
 
$linkID = @mysql_connect($dbhost,$accountname,$password)
or die("Could not connect to MySQL server");
@mysql_select_db($database) or die("Could not select database");
 
$statsresult=mysql_query("SELECT * FROM `stats` WHERE `url`='".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']."'");
if (mysql_num_rows($statsresult)==0)
{
mysql_query("INSERT INTO `stats` SET `url`='".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']."', `visits`='1'");
} else {
$statsrow=mysql_fetch_array($statsresult);
$statstotal=1+$statsrow['visits'];
mysql_query("UPDATE `stats` SET `visits`='".$statstotal."' WHERE `url`='".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']."'");
}
 
function getstats()
{
$statsresults=mysql_query("SELECT * FROM `stats` WHERE `url`='".$_SERVER['SERVER_NAME'].
$_SERVER['REQUEST_URI']."'");
$statrow=mysql_fetch_array($statsresults);
return $statrow['visits'];
unset($statsresults);
unset($statrow);
}

Then to retrieve and display what the current visitor count is simply use the below code. You may also want to use css (Cascading Style Sheets) and HTML to style up what the visitor count looks like.

echo getstats();
 
// or to put it into a sentence
 
echo "The current visitor count is ".getstats();
Personal tools
languages
page stats
Toolbox