如何防止给自己的职位投票? [英] How to prevent of giving vote to his own post?

查看:45
本文介绍了如何防止给自己的职位投票?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 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.";
}

这篇关于如何防止给自己的职位投票?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆