Online: 103   Members: 4,232

Create A Website Counter

Creating a counter, whether you wish to use a text or image based display is simpler than you might have thought. This tutorial can show you how with the use of a MYSQL table. First we need to create the table:

CREATE TABLE counter (
   id int(11) DEFAULT '0' NOT NULL auto_increment,
   name varchar(250) NOT NULL,
   count int(11) DEFAULT '0' NOT NULL,

The first field, id, is in this case rather unnecessary however it is always a good idea to include this with your tables. Our second field stores the name of the display which allows us to have multiple counters, a different one for each page perhaps. And the last field, counter, of course records the number of visits.

Now we will create the actual script, first we need to connect to our database:

$hostname = 'host';
$username = 'username';
$password = 'password';
$database = 'database';
mysql_connect($hostname,$username,$password) OR DIE("Unable to connect to
mysql_select_db("$database") or die("Unable to select database");

Now that we have made our connection, we need to make the part that gets the information from the table to display:

$name = "$counter-name";
$result = MYSQL_QUERY("SELECT * FROM counter WHERE (name = '$name')");
$row = mysql_fetch_array($result);

With all but one step complete we can move onto the code that records the hit and displays the code:

  mysql_query("UPDATE counter SET count = count+1 WHERE (name = '$name')");
  $count = $row['count'];
  mysql_query("INSERT INTO counter VALUES ('', '$name', '2')") or die("Bad
  query: ".mysql_error());
  $count = '1';

echo $count;

Related Tutorials

Useful Resources