What is the best way to count page views in PHP/MySQL?

后端 未结 8 753
[愿得一人]
[愿得一人] 2020-12-07 09:47

And by best I mean most efficient, right now placing this on my post.php file is the only thing I can think of:

$query = mysql_query(\" UPDATE posts SET view         


        
8条回答
  •  一整个雨季
    2020-12-07 10:32

    This way show how many actual people viewed your website not just how many times they viewed your website.

    Step1: Connecting to MySQL

    dbconfig.php

    try
    {
        // Returns DB instance or create initial connection
        $pdo = new PDO("mysql:host={$DB_host};port={$DB_port};dbname={$DB_name};charset=utf8mb4",$DB_user,$DB_pass);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e)
    {
         echo $e->getMessage();
    }
    

    Step2: Creating MySQL table

    --
    -- Table structure for table `unique_visitors`
    --
    
    CREATE TABLE `unique_visitors` (
      `date` date NOT NULL,
      `ip` text COLLATE utf8_unicode_ci NOT NULL,
      `views` int(1) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    

    Step3: Create a visitor counter by using IP address.

    prepare("SELECT * FROM unique_visitors WHERE date=:date");
        $stmt->execute(['date' => $date]);
    
        if(count($stmt->fetchAll()) === 0){
            // Block will execute when there is no record of current date in the database table
            $data = [
                'date' => $date,
                'ip' => $userIP,
            ];
            // SQL query for inserting new record into the database table with current date and user IP address
            $sql = "INSERT INTO unique_visitors (date, ip) VALUES (:date, :ip)";
            $pdo->prepare($sql)->execute($data);
        }else{
            $row = $stmt->fetchAll(PDO::FETCH_ASSOC);
            // Will execute when current IP is not in database
            if(!preg_match('/'.$userIP.'/i',$row['ip'])){
                // Combines previous and current user IP address with a separator for updating in the database
                $newIP = "$row[ip] $userIP";
                $data = [
                    'ip' => $newIP,
                    'date' => $date,
                ];
                $sql = "UPDATE unique_visitors SET ip=:ip, views=views+1 WHERE date=:date";
                $pdo->prepare($sql)->execute($data);
            }
        }
    ?>
    

提交回复
热议问题