我尝试让我的脚本每次IP新时都将视图计数更新+1。 604800秒后,如果同一用户(同一IP)在604800秒后再次回归,则查看次数为+ 1。 有人可以帮助我。
//Get video id
$id = $_GET['id'];
//Get video title
$videoName = $_GET['idtitle'];
//Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=videodb', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Get user IP
$ip = $_SERVER["REMOTE_ADDR"];
//Insert that user IP, Name, Title and increase view count by +1
//This is what i want to accomplish but is not working!
$insert = $pdo->query("INSERT INTO `videodb`.`videos` ( `ip`, `name`, `title`, `views`) VALUES ('$ip', '$id', '$videoName', `views`+1)");
//示例二
//Select the IP from videos
$select = $pdo->prepare("SELECT `ip` FROM `videos`");
$sql = $select->execute();
while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
//If the IP in database is not equal to the user IP in database views +1
if($row->fetch('ip') == $ip){
$pdo->query("UPDATE videos SET `views` = `views`+1 WHERE id = '$id' ");
}}
答案 0 :(得分:0)
在表格中再添加一列作为last_viewed_at DATETIME。
在将记录插入数据库之前:
当您查看过去7天的记录时,请查询如下:
$row = "SELECT * FROM videos WHERE
id = 'users.ip.to.check'";
条件:您已获得users.ip.to.check
的记录
现在检查时差是否超过7天。
装置
if (count($row) > 0) {
$ipLastViewAt = new \DateTime($row['last_viewed_at']);
$currentDate = new \DateTime();
$diff = $currentDate->diff($ipLastViewAt)->format("%a");
if ($diff >= 7 ) {
// update the record with the view + 1 and with last_view_at = currentDateTime;
}
} else {
// Insert the record with the view +1 and with last_view_at = currentDateTime;
}
答案 1 :(得分:0)
提示:两张表可能更好,一张保存视频信息,另一张保存访客信息
videos:id,ip,name,title,views,update_time
// first, select $video info and get the result --- "select * from videos where ip='{$ip}' and id='{$id}'";
// we got $video look like : array('id'=>1,'update_time'=>'1453970786')
$time = time();
if( isset($video['id']) && (($time - $video['update_time']) >= 604800) ){
$pdo->query("UPDATE `videodb`.`videos` SET `views`=`views`+1 AND update_time='$time' WHERE id = '$id'");
}elseif( !isset($video['id']) ){
$pdo->query("INSERT INTO `videodb`.`videos`( `ip`, `name`, `title`, `views`) VALUES ('$ip', '$id', '$videoName', 1)");
}
$pdo->query("INSERT INTO `videodb`.`videos`(`id`, `ip`, `name`, `title`, `views`) VALUES ('$id','$ip', '$id', '$videoName', 1)");
答案 2 :(得分:0)
如果Ip是唯一字段,则此查询应该有帮助
INSERT INTO `videodb`.`videos`( `ip`, `name`, `title`, `views`) VALUES ('$ip', '$id', '$videoName', 1) ON DUPLICATE KEY UPDATE `views`=views+1;