Counter files

A counter is an essential part of a site to know how many people are coming to site.

The first step is to create the counter table .

You can dump the structure from counter.sql into your phpMyAdmin if you use it.This is going to create a small table to store hits for each page it counts.

-- Table structure for table counter

--



CREATE TABLE `counter` (

`id` int(11) NOT NULL auto_increment,

`page` text NOT NULL ,

PRIMARY KEY (`id`)

)

Once your table is setup, we'll begin building the counter.

code.php contains the code that needs to be place on each page that needs the counter.

<?php

$dbsrv = "localhost";

$db = "counter_db";

$user = "root";

$user_password ="root";

$dblnk = mysql_connect($dbsrv,$user,$user_password);

$rez = mysql_select_db($db, $dblnk);

?>

In code.php we must include "define.php".

It contains the database name, server name, username and password . A connection to the database will be established within this file.

It will be included in all files that will use a database connection . If you modify any of these variables like username or password you won't have to modify each file where you have a database connection , only this file , define.php . Of course, it is possible to place the connection string within each file instead of using the include directive, but when you will need to modify a variable you will have to find and modify each line where you use a database connection.

code.php:

<?

include ("define.php");

$page = $_SERVER['REQUEST_URI'];

$sql = "INSERT INTO counter(page) values ('$page')";

$rez =mysql_query($sql,$dblnk);

$query = "SELECT count(*) as page_hits FROM counter WHERE page='$page'";

$sql = mysql_query($query);

$array = mysql_fetch_array($sql);

$hits = $array[page_hits];

print "This Page Has Had $hits Views";

?>

Variable $page is initialized using page's URI .Then, this values is inserted into the database (line 4).

Now we can display the counter using a simple query . The sql query will return the number of hits for the page where we are located (line 14)
.

Now the number of hits can be displayed. Everytime the page is refreshed a new record will be inserted into the database and the counter is incremented.

admin – Thu, 2005 – 07 – 07 15:49