I have a comics website where I’m trying to implement a like/dislike system. Each user can only vote once on a particular comic. The comics are stored in ‘comics’ table, artwork stored in ‘artwork’, and I have a ‘votes’ table with columns (ip, table_name, imgid).
When someone votes, I want to store their IP against that image id and table within “votes” table. If they try to vote again, it will check that table to see if they have voted.
Also, I want to do a ON DUPLICATE KEY UPDATE which will update the Primary Key “ip” in the votes table if someone with that IP tries to vote again.
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);
Any thoughts?
tableis a reserved word in MySQL. If you want to use it, you have to enclose it in backticks. In your case, however, I think that the you meant to usetable_nameinstead:From the syntax of your query, you should consider using
REPLACE:So your query would resolve to this: