Creating a php/MySQL Hit Counter

I am not sure how many people actually use a hit counter anymore, but I have installed one on my personal site, to keep up with the post views. When I wrote the database, I included the hits and just decided to make that information public knowledge. I have a couple of posts that have had over 17000 views in the past couple years which isn’t too bad.

Anyway, to write the hit counter, you will need to create a new table in the database. I simply name the table hits but you can name it whatever you like to make it work with your database structure (i.e. wp_hits, etc.)

To do this from phpMySQLAdmin, you will need to run the following query on the database:

CREATE TABLE `hits` (`hits` int(11) not null);
INSERT INTO `hits` (`hits`) VALUE (0);

You can write a simple php script to install it as well (be sure that you connect to the database first.)

$server = ‘host’;
$username = ‘username’;
$password = ‘password’; // MySql Password
$database = ‘databasename’; // MySql Database
$con = mysql_connect(“$server”,”$username”,”$password”);
if (!$con) { die(‘Could not connect: ‘ . mysql_error()); }
mysql_select_db(“$database”, $con);
mysql_query(“CREATE TABLE `hits` (`hits` int(11) not null); “);
mysql_query(“INSERT INTO `hits` (`hits`) VALUE (0); “);

Now your database will use this table to keep up with your total page views once you implement the code into the script.

To implement the code into the script, find a file that loads on every page view such as header or configuration or something along those lines. At the top of that page, you will want to add the following code:

mysql_query(“UPDATE hits` SET `hits` = hits + 1 “);

That will update the database with the correct number of hits after the page loads.

To display the hits, in the footer of the script add the following code:
    mysql_query(“UPDATE hits` SET `hits` = hits + 1 “);
    $h = $row[‘hits’];
    echo ‘Total Views ‘.$h;

You can do like I did and create custom images with letters to display practically any font and style that you like. To make the replacements, use the php str_replace statement to replace the number with the image. You can also create each letter of the alphabet or a custom image for to replace Total Views.

To see the code in action, visit This is one of the pages with over 17000 views.



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.