Tuesday, March 28, 2017

How to Create Visitors counter by IP address in php pdo




This Tutorial is about How to Create Visitors counter by IP address in php pdo
First Create the database and name it as view and then create table

 

Table structure for table `visitors`

CREATE TABLE `visitors` (
  `id` int(11) NOT NULL,
  `ip` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `visitors`
--
INSERT INTO `visitors` (`id`, `ip`) VALUES
(2, ''),
(3, ''),
(4, '::1'),
(5, '127.0.0.1');

<?Php
    $dbhost = 'localhost';
    $dbname = 'views';
    $dbuser = 'root';                
    $dbpass = '';
  
  
    try{
      
        $dbcon = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
        $dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      
    }catch(PDOException $ex){
      
        die($ex->getMessage());
    }
  
?>
<?php
        $ip = $_SERVER['REMOTE_ADDR'];
         $stmt = $dbcon->prepare("SELECT ip  FROM visitors WHERE ip= '$ip'");
         $stmt->execute();
         $stmt1=$stmt->rowCount();
         if ($stmt1==0) {
              $stmt2 = $dbcon->prepare("INSERT INTO visitors(id, ip) VALUES(NULL, '$ip')");
              $stmt2->execute();
         }
         $stmt = $dbcon->prepare('SELECT * FROM visitors');
        $stmt->execute();
       
        while($row=$stmt->fetch(PDO::FETCH_ASSOC))
        {
            extract($row);
             
            echo $row['ip'];
           
        }
       
        ?>

No comments:

Post a Comment