如何防止投票给自己的帖子?

时间:2015-12-18 20:30:06

标签: php mysql

我有一个名为 Votes 的表,如下所示:

// Votes
+----+---------+------------+---------+-------+------------+
| id | post_id | table_code | user_id | value | timestamp  |
+----+---------+------------+---------+-------+------------+
| 1  |  1424   | 2          | 433     | 1     | 1445898101 |
| 2  |  53431  | 4          | 54      | -1    | 1443891149 |
  .     .        .         .       .
  .     .        .         .       .  
+----+---------+---------+-------+------------+

现在我想知道,我应该如何检查Votes表新投票是属于他自己的帖子还是该帖子来自其他人?我应该检查一下$_SESSION['user_id']吗?

3 个答案:

答案 0 :(得分:2)

你应该在他们试图投票时检查这一点,并且不允许投票。查询如下:

SELECT author_id
FROM Posts
WHERE id = $_POST[post_id]

然后检查作者是否与当前用户相同:

if ($row['author_id'] == $_SESSION['user_id']) {
    echo "You can't vote on your own posts!";
} else {
    // insert into Votes table
}

如果您想要检查INSERT查询,可以这样做:

INSERT INTO Votes (post_id, user_id, value, timestamp)
SELECT $post_id, $user_id, $value, $timestamp
FROM DUAL
WHERE $user_id != (SELECT author_id FROM Posts WHERE id = $post_id)

然后报告错误,您可以获得受查询影响的行数;如果这是0,则表示他们试图在自己的帖子上投票。

if (mysqli_affected_rows($conn) == 0) {
    echo "You can't vote on your own posts!";
} else {
    echo "Thank you, your vote has been recorded.";
}

答案 1 :(得分:1)

您可以在MySQL查询中进行检查。不要忘记防止MySQL注入。不是100%肯定语法,但这应该给你一个好主意。

$answer = $MySQL->query("UPDATE Votes SET ['value'] = (['value']+1) WHERE post_id = ".$post_id." AND user_id != ".$SESSION['user_id']);
if($answer) return "Upvoted";
else return "Can't upvote yourself !";

编辑:

您实际上应首先检查您的帖子表

$userWhoPosted= $MySQL->query("SELECT user_id FROM Post WHERE post_id = ".$post_id);
if($userWhoPosted != $_SESSION['user_id']){
    $answer = $MySQL->query("INSERT INTO Votes (post_id,user_id,value,timestamp) VALUES (".$post_id.",".$user_id.",".$value.",".$timeStamp.")  ")
}  
else return "Can't upvotes yourself";

编辑2:

$answer = $MySQL->query("INSERT INTO Votes (post_id,user_id,value,timestamp) VALUES (".$post_id.",".$user_id.",".$value.",".$timeStamp.") WHERE user_id != (SELECT user_id FROM Post WHERE post_id = ".$post_id.")  ")

答案 2 :(得分:0)

您没有向我们提供足够的信息,但MySQL中有一个经典的解决方案

CREATE TABLE Votes
(
// your fields here
CONSTRAINT uc_post_user_vote UNIQUE (post_id,user_id,value)
)

这意味着一位用户无法为同一帖子投票或投票两次。 想想这个,我希望它会帮助你。