I have a comics website where I'd like to allow users to vote once per comic and once per piece of artwork.
There seems to be two problems with my code:
1) I only want one user voting once per image... so I want to capture their information and store it in a database. I have a ON DUPLICATE KEY UPDATE, but it gives me the following syntax error even though I haven't found ANYTHING wrong with it:
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
An example of it allowing multiple entries into the database for the same IP:
2) It's still allowing one user to vote multiple times.
$sql = "SELECT ip FROM votes WHERE ip = \"".$_SERVER['REMOTE_ADDR']."\" AND table_name = $table AND imgid = $imgid";
$result = $mysqli->query($sql);
var_dump($result);
Full code:
<?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);
?>
Echoing out sql:
echo "sql: ". $sql;
Produces:
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)
Any help would be greatly appreciated!