仅通过MYSQL爆炸允许1次Upvote

时间:2015-07-17 20:30:23

标签: php mysql mysqli

我正在我的网站上创建一个upvote系统。目前,upvotes正在运行,但我想将upvotes限制为每个用户1。 通过更新总票数来添加投票:

mysqli_query($connection,"UPDATE news SET votes=(votes + 1) WHERE ID='". $_POST['id1'] . "'");

然后我记录用户使用以下内容对该文章投票:

mysqli_query($link,"UPDATE users SET votes=CONCAT(votes,'" . $_POST['id1'] .",') WHERE ID='". $_SESSION['ID'] . "'");

现在,如果文章ID不在他们的“投票”数据库中,我尝试实现仅允许upvote。我正在存储像1,4,7,12这样的投票,以便用户对第1,4,7和12条投票。所以我试图使用explode来检查他们是否已经投了一篇文章:

$results = mysqli_query($link2,"SELECT * FROM users WHERE ID ='" . $_SESSION['ID'] . "'");

while($result = mysqli_fetch_array( $results )){

  $votes = explode(",", $result['votes']);

  foreach($votes as $vote) {

  if ($vote = $_POST['id1']) {
//Do nothing
} else {
mysqli_query($connection,"UPDATE news SET votes=(votes + 1) WHERE ID='".     $_POST['id1'] . "'");
mysqli_query($link,"UPDATE users SET votes=CONCAT(votes,'" . $_POST['id1'] .",') WHERE ID='". $_SESSION['ID'] . "'");

非常感谢有关更好地完成同样事情的任何帮助或建议,谢谢!

1 个答案:

答案 0 :(得分:1)

使用投票表:

CREATE TABLE voted (
   user_id INT NOT NULL,
   news_id INT NOT NULL,
   FOREIGN KEY (user_id) REFERENCES user(id),
   FOREIGN KEY (news_id) REFERENCES news(id)
) ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=4;

在此添加唯一约束:

CREATE UNIQUE INDEX idx_voted_nn_1 ON voted (user_id,news_id);

然后使用一些在约束问题上退出的PHP代码:

$connection = new mysqli("example.com", "user", "password", "database");
$query="INSERT INTO voted (user_id,news_id) VALUES (?,?)";
$stmt=$connection->query($query);
$stmt->bind("ii",$_SESSION['ID'],$_POST['ID']);
$stmt->execute();
$error=$mysqli_stmt->errno($stmt);
if(!$error) update your news vote;
else do nothing or say something to user;