Clan Adverts

PHP Web Host - Quality Web Hosting For All PHP Applications

 

Make A Page Hit Counter

Description: How to make a PHP hit counter using PHP and MySql. This is a basic text counter that will count every time your page is loaded...
Version: 1.0
Added on: 22 May 2007
Author: ped
Difficulty Level: Intermediate
Views: 290
Detailed Profile

First thing we need to do is make a MySql database, this is done from within the CPanel of your hosting account... I'm not going to go into how to set up the MySql database as I hope if you are reading this tutorial you at least know that much....

Now we have to make tables in the new database, These tables will be..



id    This is the id of the counter and will be unique to each counter you may start..


count    This is the actual number of times the page has been loaded..


We will make a script to help us make the tables for the database, we will call this script setup.php.....

Code:
<?
$dbh = mysql_connect(localhost,DBUSER,DBPASS) or die("Cannot connect database");
mysql_select_db(DATABASE) or die( "Unable to select database");


mysql_query("CREATE TABLE counter (id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
count VARCHAR(30)NOT NULL)")
or die(mysql_error());
mysql_query("INSERT INTO counter
(count) VALUES('0') ")
or die(mysql_error()); ?>
echo "<p align=center><b><font face=Verdana size=4>Counter database successfully created..";
?>


Notice in the 2nd line of the setup.php file where it says DBUSER and DBPASS, you need to change those to the user and password you made when you set up your database..... And on the 3rd line where it says DATABASE, you need to change that to the name of your database.

Next we need to make the PHP file that will query the database to retrieve the current count, add 1 to that number, update the database with the new hit count and print out the new hit count, we will call this file count.php...

Code:
<?
$dbh = mysql_connect(localhost,DBUSER,DBPASS) or die("Cannot connect database");
mysql_select_db(DATABASE) or die( "Unable to select database");

$sql = "SELECT id, count, url, FROM counter WHERE id = 1";
$result = mysql_query($sql);
if (!$result)
{
echo 'Error with the query. Message returned: ' .
mysql_error();
die;
}
while ($row = mysql_fetch_assoc($result))

$count = $row['count']+1;


$query = "UPDATE counter SET count = '$count' WHERE id = 1";
mysql_query($query);


echo "$count";

?>


Now that we have all the PHP files we need we can now upload the files to the web server... After both files are uploaded we need to call the setup.php file from our web browser like this:

http://YOURDOMAINNAME.com/COUNTER_DIRECTORY/setup.php

That will now set up the tables needed to keep the counter numbers in... YOU SHOULD NOW REMOVE THE SETUP FILE FROM YOUR WEB SERVER...

Now we can simply include it in any PHP file with the PHP include like:



That's it, you should now se the counter on your PHP page

I hope this short tutorial helps you out...