我最近为我的漫画网站实现了自定义喜欢和不喜欢的功能。我想让用户通过“取消点击”喜欢或不喜欢按钮来“收回”他们的选择。
我的功能通过以下方式工作:
1) 通过 Jquery 将按钮值 (id = 'like' 或 id = 'dislike') 传递给 php 脚本
2) 脚本将首先根据给定的漫画 ID 检查数据库中是否存在 IP……如果不存在,它将插入用户的 IP 和当前漫画 ID……如果存在,它最初说“你已经投票”。 ..但现在要实现“不喜欢”,我只会让它运行一个删除查询
3)然后它将获得该漫画ID和增量的当前总喜欢。
我认为可以做到的方式是,如果用户再次按下按钮,我基本上会运行相反的查询...根据该漫画 ID 从表中删除该用户的投票...然后减少漫画中该图像的总喜欢桌子。
所以我的问题是,
1)如果他们按下一个按钮一次,则执行插入查询,如果他们“取消选择”相同的选择,则执行删除查询是实现此操作的最佳方式?用户不能通过不断地按赞按钮发送垃圾邮件和使数据库过载,从而不断地喜欢和不喜欢吗?我应该为该 ID 实现某种 $_SESSION['count'] 吗?
2)如果我要存储某个IP...如果几个唯一用户碰巧在...使用同一台计算机会发生什么...比方说网吧...它将始终存储该用户的IP。针对 IP 存储是最好的方法吗?
如果您需要参考代码:
<?php
include 'dbconnect.php';
$site = $_GET['_site'];
$imgid = intval($_GET['_id']);
$input = $_GET['_choice'];
if ($site == "artwork") {
$table = "artwork";
}
else {
$table = "comics";
}
$check = "SELECT ip, tablename, imgid FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND tablename = '$table' AND imgid = $imgid";
$result = $mysqli->query($check);
if ($result->num_rows == 0) {
//Insert voter's information into votes table
$sql = "INSERT INTO
votes (ip, tablename, imgid)
VALUES
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)
ON DUPLICATE KEY UPDATE
imgid = VALUES(imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
/*while ($row = $result->fetch_assoc()) {
echo "you've inserted: " . $row['ip'] . ", " . $row['tablename'] . ", " . $row['imgid'] . ".";
}*/
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") {
$sql = "UPDATE $table SET like_count = like_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes++;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes++;
}
}
else { //"unlike" their previous like for that given image id
$sql = "DELETE FROM
votes
WHERE (ip, tablename, imgid) =
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") { //remove like
$sql = "UPDATE $table SET like_count = like_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes--;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes--;
}
}
echo "Likes: " . $likes . ", Dislikes: " . $dislikes;
mysqli_close($mysqli);
?>