如何防止给自己的职位投票?
我有一个名为 Votes 的表,如下所示:
I have a table named Votes like this:
// 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']
吗?
Now I want to know, how should I check Votes
table that the new vote is belong to his-own-post or that post is from other guy? Should I check $_SESSION['user_id']
with what?
您应该在他们尝试投票时检查这一点,并且不允许投票.执行如下查询:
You should check for this when they're trying to vote, and not allow the vote. Do a query like:
SELECT author_id
FROM Posts
WHERE id = $_POST[post_id]
然后检查作者是否与当前用户相同:
Then check if the author is the same as the current user:
if ($row['author_id'] == $_SESSION['user_id']) {
echo "You can't vote on your own posts!";
} else {
// insert into Votes table
}
如果你想在INSERT
查询中进行检查,你可以这样做:
If you want to do the check in INSERT
query, you can do it like this:
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
,则表示他们试图对自己的帖子进行投票.
Then to report the error, you can get the number of rows affected by the query; if this is 0
, it means they tried to vote on their own post.
if (mysqli_affected_rows($conn) == 0) {
echo "You can't vote on your own posts!";
} else {
echo "Thank you, your vote has been recorded.";
}