在PHP / MySQL中计算页面视图的最佳方法是什么?

时间:2011-01-21 18:40:25

标签: php mysql

最好的意思是效率最高,现在将它放在我的post.php文件中是我唯一能想到的:

$query = mysql_query(" UPDATE posts SET views + 1 WHERE id = '$id' ");

有更好的方法,一种消耗更少服务器资源的方法。我问,因为如果这是一个小应用程序我会对上面没有问题,但我正在尝试构建一些将被很多人使用的东西,我希望尽可能地提高查询性。

8 个答案:

答案 0 :(得分:57)

如果您对保存资源感兴趣并且仍然使用SQL进行报告,并且精确#无关紧要,您可以尝试这样的采样(修改采样率以适合您的比例):

$sample_rate = 100;
if(mt_rand(1,$sample_rate) == 1) {
    $query = mysql_query(" UPDATE posts SET views = views + {$sample_rate} WHERE id = '{$id}' ");
    // execute query, etc
}

答案 1 :(得分:17)

如果memcache是​​您服务器环境中的一个选项,这是另一种很酷的采样方式,但也能跟上准确的数字(与我的其他答案不同):

function recordPostPageView($page_id) {
    $memcache = new Memcached(); // you could also pull this instance from somewhere else, if you want a bit more efficiency*

    $key = "Counter for Post {$page_id}";

    if(!$memcache->get($key)) {
        $memcache->set($key, 0);
    }

    $new_count = $memcache->increment($key);

    // you could uncomment the following if you still want to notify mysql of the value occasionally
    /*
    $notify_mysql_interval = 100;
    if($new_count % $notify_mysql_interval == 0) {
        $query = mysql_query("UPDATE posts SET views = {$new_count} WHERE id = '{$page_id}' ");
        // execute query, etc
    }
    */

    return $new_count;
}
  • 并不介意纯粹主义者对单身人士的侮辱。或者你可以将它传递给这个函数,如果你比实用主义者更纯粹:)

答案 2 :(得分:6)

恕我直言最佳解决方案是将views_count存储在内存中(memcached,等等), 并在内存中进行更新。 (当然更新必须同步)

然后你可以使用cron脚本将这些值推送到db。 (经过一段时间 - 秒,分钟,等等。)

答案 3 :(得分:4)

您还可以检查这些代码行。我认为这将有所帮助,因为您只需一个文本文件即可实现目标。它不需要任何数据库活动。



<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
  $f = fopen($counter_name, "w");
  fwrite($f,"0");
  fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
  $_SESSION['hasVisited']="yes";
  $counterVal++;
  $f = fopen($counter_name, "w");
  fwrite($f, $counterVal);
  fclose($f); 
}
echo "You are visitor number $counterVal to this site";
&#13;
&#13;
&#13;

答案 4 :(得分:3)

在数据库中只有一列ip定义了主键,然后使用以下PHP代码将ip存储在数据库中:

连接文件:

<?php 
$conn = mysqli_connect("localhost","root","");
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$db=mysqli_select_db($conn,"DB_NAME");
if(!$db)
{
    echo "Connection failed";
}
?>

PHP文件:

<?php
$ip=$_SERVER['REMOTE_ADDR'];
$insert="INSERT INTO  `id928751_photography`.`ip` (`ip`)VALUES ('$ip');";
$result = mysqli_query($conn,$insert);
?>

显示计数:

<?php
$select="SELECT COUNT(ip) as count from ip;";
$run= mysqli_query($conn,$select);
$res=mysqli_fetch_array($run);
echo $res['count'];
?>

在数据库中使用此方法存储所有服务器ip

注意:只有服务器ip可以存储或计数不是设备IP

答案 5 :(得分:2)

您可以在缓存中保留一个反数组(如APC或Memcache),并增加其中某些帖子的计数器。然后暂时存储更新。如果发生缓存重置

,您可能会丢失一些视图

其他解决方案是仅为访问保留一个单独的表(字段:postid,visits)。这是你可以从mysql获得的东西。尝试使用InnoDB引擎,因为它提供行级锁定!

答案 6 :(得分:0)

这种方式显示的是实际访问过您网站的人数,而不只是他们浏览您网站的次数。

第一步:连接到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();
}

第二步:创建MySQL表

--
-- 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;

第3步:使用IP地址创建访客计数器。

<?php
    require_once("dbconfig.php");
    // Returns current date in YYYY-MM-DD format
    $date = date("Y-m-d");
    // Stores remote user ip address
    $userIP = $_SERVER['REMOTE_ADDR'];
    // Query for selecting record of current date from the table
    $stmt = $pdo->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);
        }
    }
?>

答案 7 :(得分:0)

<?php
session_start();
$counter_name = "counter.txt";
// Check if a text file exists. If not create one and initialize it to zero.
if (!file_exists($counter_name)) {
  $f = fopen($counter_name, "w");
  fwrite($f,"0");
  fclose($f);
}
// Read the current value of our counter file
$f = fopen($counter_name,"r");
$counterVal = fread($f, filesize($counter_name));
fclose($f);
// Has visitor been counted in this session?
// If not, increase counter value by one
if(!isset($_SESSION['hasVisited'])){
  $_SESSION['hasVisited']="yes";
  $counterVal++;
  $f = fopen($counter_name, "w");
  fwrite($f, $counterVal);
  fclose($f); 
}
echo "You are visitor number $counterVal to this site";