0

我有一个漫画网站,我正在尝试实现一个喜欢/不喜欢的系统。每个用户只能对特定漫画投票一次。漫画存储在“漫画”表中,艺术品存储在“艺术作品”中,我有一个带有列(ip、table_name、imgid)的“投票”表。

当有人投票时,我想将他们的 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);

有什么想法吗?

4

2 回答 2

1

tableMySQL 中的保留字。如果要使用它,则必须将其括在反引号中。但是,在您的情况下,我认为您打算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)";
于 2012-11-24T17:25:57.407 回答
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” . 列“表”在这里不存在。只需将其更改为“table_name = VALUES(table_name)”。

于 2012-11-24T17:29:47.257 回答