1. About.com
  2. Computing & Technology
  3. PHP / MySQL

Discuss in my forum

Web Page Hit Counter

Web Site Hit Counter Code Using PHP and MySQL

By , About.com Guide

A hit counter is a line of code that shows how many visitors have been to your web page. We will store the total amount of hits in a MySQL database. To do this we first need to create a table to hold the counter statistics. To do that we need to execute this code:
 CREATE TABLE `counter` ( `counter` INT( 20 ) NOT NULL );
 INSERT INTO counter VALUES (0); 
What this does is create that table "counter" with single field also called "counter." This is where we will store the number of hits our site has. It is set to start at 1, and we will add one each time the file is called, and then display the new number. That is done with this code:
 <?php
 // Connects to your Database 
 mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); 
 mysql_select_db("Database_Name") or die(mysql_error()); 

//Adds one to the counter mysql_query("UPDATE counter SET counter = counter + 1");

//Retreives the current count $count = mysql_fetch_row(mysql_query("SELECT counter FROM counter"));

//Displays the count on your site print "$count[0]"; ?>

Counter Code Tips
1.) Hold the counter in a separate file and retrieve it using include ()
2.) Format the counter text using regular HTML around the include
3.) Try creating different rows on the counter table for additional pages.

©2012 About.com. All rights reserved. 

A part of The New York Times Company.