<?php
//引入memcached
require_once '../class/memcached.class.php';
//连接MySQL
$link = mysqli_connect("localhost", "root", "", "laravel");
//给memcached传值
$mc = new memcached(array(
'servers' => array('127.0.0.1:11211'),
'debug' => false,
'compress_threshold' => 10240,
'persistant' => true,
));
//获取文章id
$id = $_GET['id'];
//设置key
$key = "news_click_" . $id; // 33 100 news_click_33 102
//获取key
$click = @$mc->get($key);
//如果内存中没有
if ($click === null) {
//如果内存中没有,去数据库读点击数
//根据id,读文章记录
$sql = "select clicknum from news where id=$id";
//执行
$result = mysqli_query($link, $sql);
//获取结果
$arr = mysqli_fetch_assoc($result);
//获取浏览量
$click = $arr['clicknum'];
//自增浏览量
$click++;
//添加内存
$mc->add($key, $click);
} else {
//如果有内存, 直接自增值
$mc->incr($key, 1);
//本次访问量+1
$click++;
//减少数据库压力,5次一蹦
if ($click % 5 == 0) {
$sql = "update news set clicknum=$click where id=$id";
mysqli_query($link, $sql);
}
}
//数据库表中,记录的点击数要自增1
echo "document.write('{$click}')";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>隔壁老王,帮助别人,从不留名</h1> <div>发布时间:2018-07-03 点击数:
<script type="text/javascript" src="click.php?id=1"></script>
</div> <hr/>
<div>很随便</div>
</body>
</html>