我有一个漫画网站,我想允许用户为每部漫画和每件艺术品投票一次。
我的代码似乎有两个问题:
1)我只希望一个用户对每张图像投票一次......所以我想捕获他们的信息并将其存储在数据库中。我有一个 ON DUPLICATE KEY UPDATE,但它给了我以下语法错误,即使我没有发现它有任何问题:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table = VALUES(table), imgid = VALUES(imgid)' at line 7
一个允许同一 IP 进入数据库的多个条目的示例:
2)它仍然允许一个用户多次投票。
$sql = "SELECT ip FROM votes WHERE ip = \"".$_SERVER['REMOTE_ADDR']."\" AND table_name = $table AND imgid = $imgid";
$result = $mysqli->query($sql);
var_dump($result);
完整代码:
<?php
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 = VALUES(table),
imgid = VALUES(imgid)";
$mysqli->query($sql);
echo $mysqli->error;
echo "<br/>";
$sql = "SELECT ip FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND table_name = '$table' AND imgid = $imgid";
$result = $mysqli->query($sql);
echo $mysqli->error;
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";
}
mysqli_close($mysqli);
?>
回显sql:
echo "sql: ". $sql;
产生:
sql: INSERT INTO votes (ip, table_name, imgid) VALUES ("127.0.0.1", "comics", 34) ON DUPLICATE KEY UPDATE ip = VALUES(ip), table = VALUES(table), imgid = VALUES(imgid)
任何帮助将不胜感激!