Friday, July 31, 2015

How to Create Visitor Counter using PHP and Mysql

You might have seen visitor counter on many websites. Visitor counter is a simple script which is used to show number of visits on your webpage. This Post will explain you the simple  code to create your own  visitor counter using PHP and Mysql. You can use this code in any of your web applications to keep track on your visitors number in database for analysis 



Just Follow Two Simple Steps to create your own visitor counter using PHP and Mysql in your Web application

  1. 1.       Create a Table in your database
  2. 2.       Create a test file to implement the code (counter.php) 


Step 1: Create Table in your database 


Simply make a table with name tbl_counter(any name) in your database to keep the records of visitors.


CREATE TABLE `tb_counter` (
`counter` INT( 11 ) NOT NULL AUTO_INCREMENT ,
PRIMARY KEY ( `counter` )

) ENGINE = MYISAM ;






Step 2: Create a php file (Test File) 

Just implement the below mentioned code in your test file after creating table in your database

<?php
session_start();
require_once 'db_con.php';

$counter='';//initilize counter
$sql="SELECT counter FROM tbl_counter";
$resultc=mysql_query($sql);
$rows=mysql_fetch_assoc($resultc);
$counter=$rows['counter'];
// if count is empty
if(empty($counter)){
$counter=1;
$insertCounter="INSERT INTO tbl_counter set counter='".$counter."'";
$result1=mysql_query($insertCounter);
}



// increment visitor count
$increasecounter=$counter+1;
$sql2="update tbl_counter set counter='".$increasecounter."'";
$result2=mysql_query($sql2);



?>
<!DOCTYPE HTML>
<html>
    <head>
        <title>
            Hits Counter
        </title>
    </head>
    <h1>
      <?php echo "Total hits in this page=" .$counter ; ?>
    </h1>
</html>

Now you are done. Execute the code in your browser.Your own visitor counter using PHP and Mysql is ready to work now

To know more  watch my video tutorial in you tube to know more











Enjoy!!!
Hopefully this simple script helped you with your web development.
If you like this post, Please follow us and share our post via social button and help spread the word. We need your support to continue.

No comments:

Post a Comment