Visitor Counter Script Using PHP


If you have noticed that many websites display visitor's number on site.In this tutorial I am going to explain you how to create a simple visitor counter script using php.

First of create table called "visitor_counter" by executing the below SQL statement.

Step1: Creating Table

CREATE TABLE `visitor_counter` ( `counts` int(10) NOT NULL default '0' )

Now create one file called "counter.php" and paste the below content.

Step2:  counter.php File

// Database Details
$host     = "localhost";
$username = "root";
$password = "";
$db_name  = "test";
$tbl_name = "visitor_counter";

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or 
die("cannot connect to server ");
mysql_select_db("$db_name")or die("cannot select DB"); 

$sql      = "SELECT * FROM $tbl_name";
$result   = mysql_query($sql);
$rows     = mysql_fetch_array($result);
$counter  = $rows['counts'];

// setting counter = 1, if we have no counts value 
$counter = 1;
$sql1    = "INSERT INTO $tbl_name(counts) VALUES('$counter')";
$result1 = mysql_query($sql1);

echo "You 're visitors No. "; 
echo $counter; 

// Incrementing counts value 
$sql2    = "update $tbl_name set counts='$plus_counter'";
$result2 = mysql_query($sql2); 


Script Logic

(1) Database Connection
- You just have to provide the database credentials to connect with your database.

(2) Select Total Numbers of Users
- Execute simple select query to get the total count from the database table. if total = 0 means first visitor in this case insert the value in table.

(3) Display Record
- Display the total count as visitor Count

(4) Increment
- Increment the total number by 1 to update the total numbers of counts.

Thats it..!! your simple visitor counter script with php and mysql is ready. Share this script with your friends.

Similar script : Online Users Script Using PHP and MySQL