我有一个漫画网站,我正在尝试实现喜欢/不喜欢的系统。每个用户只能对特定漫画投票一次。漫画存储在“漫画”表中,艺术品存储在“艺术品”中,我有一个带有列(ip,table_name,imgid)的'votes'表。
当有人投票时,我想将他们的IP存储在“投票”表格中的图像ID和表格中。如果他们再次尝试投票,它将检查该表以查看他们是否已经投票。
另外,我想做一个ON DUPLICATE KEY UPDATE,如果有IP的人试图再次投票,将更新投票表中的主键“ip”。
include 'dbconnect.php';
$site = $_GET['_site'];
$imgid = intval($_GET['_id']);
$input = $_GET['_choice'];
if ($site == "artwork") {
$table = "artwork";
}
else {
$table = "comics";
}
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
$sql = "INSERT INTO
votes (ip, table_name, imgid)
VALUES
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)
ON DUPLICATE KEY UPDATE
ip = VALUES(ip),
table_name = VALUES(table_name),
imgid = VALUES(imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
$sql = "SELECT ip FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND table_name = '$table' AND imgid = $imgid";
if ($result = $mysqli->query($sql)) {
if ($result->num_rows == 0) {
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++;
}
echo "Likes: " . $likes . ", Dislikes: " . $dislikes;
}
else {
echo "You have already voted";
}
}
else {
printf("Error: %s\n", $mysqli->error);
}
mysqli_close($mysqli);
有什么想法吗?
答案 0 :(得分:1)
table
是reserved word in MySQL。如果你想使用它,你必须将它包含在反引号中。但是,在您的情况下,我认为您打算使用table_name
代替:
$sql = "INSERT INTO
votes (`ip`, `table_name`, `imgid`)
VALUES
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)
ON DUPLICATE KEY UPDATE
`ip` = VALUES(`ip`),
`table_name` = VALUES(`table_name`),
`imgid` = VALUES(`imgid`)";
根据查询的语法,您应该考虑使用REPLACE
:
REPLACE的工作原理与INSERT完全相同,只是如果表中的旧行与PRIMARY KEY或UNIQUE索引的新行具有相同的值,则在插入新行之前删除旧行。
因此,您的查询将解决此问题:
$sql = "REPLACE INTO
votes (`ip`, `table_name`, `imgid`)
VALUES
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)";
答案 1 :(得分:1)
$sql = "INSERT INTO
votes (ip, table_name, imgid)
VALUES
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)
ON DUPLICATE KEY UPDATE
ip = VALUES(ip),
table = VALUES(table),
imgid = VALUES(imgid)";
你的列是“ip”,“table_name”和“imgid”所以当你设置VALUES时它除了列名作为VALUES()的参数+你写了“table = VALUES(table)”而你的列名是“表格名”。此处不存在列“表”。只需将其更改为“table_name = VALUES(table_name)”。