2015-06-25 74 views
2

我得到了下面的代码:如果检查选择查询语句被忽略

if(isset($_POST['vote'])){ 

     if (!$wgUser->isLoggedIn()) { 
      // User is not online, don't accept the vote, set error message 
      $msg = 'Login required to vote.'; 
     } if ($wgUser->isBlocked()) { 
      // User is banned, don't accept the vote, set error message 
      $msg = 'Account is banned.'; 
     } else { 
      // User is online and not banned 
      $buildId = htmlspecialchars($_POST['id'], ENT_QUOTES, 'UTF-8'); 
      $rating = htmlspecialchars($_POST['rating'], ENT_QUOTES, 'UTF-8'); 
      $comment = htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8'); 
      $res = $db->select(
       'build_rating', 
       array('article_id', 'username', 'vote', 'comment', 'date'), 
       array('article_id' => $buildId, 'username' => $wgUser->getName()), 
       __METHOD__ 
      ); 

      // Did user already vote on this build? 
      if (!$res) { 
       // Yes, let's update the vote and set success message 
       $db->update(
        'build_rating', 
        array('vote' => $rating, 'comment' => $comment), 
        array('article_id' => $buildId, 'username' => $wgUser->getName()), 
        __METHOD__ 
       ); 
       $msg = 'Your vote has been successfully updated.'; 

      } else { 
       // No, let's insert the vote and set success message 
       $db->insert(
        'build_rating', 
        array('article_id' => $buildId, 'username' => $wgUser->getName(), 'vote' => $rating, 'comment' => $comment), 
        __METHOD__ 
       ); 
       $msg = 'Your vote has been successfully saved.'; 
      } 
     } 
    } 

是suposed保存用户评级的具体条款。除了检查用户是否已经投票的if语句(在这种情况下,它应该只是更新评分)或者它是全新的投票(在这种情况下,它应该将其保存为新的投票)之外,似乎一切正常工作。由于某些原因,因为每个投票都被保存为新投票,所以if语句不起作用。用户可以简单地放置100张选票,而实际上只能放置每篇文章一张。有人能指出我的错误吗?

+0

在存入数据库时​​,不应该使用'htmlspecialchars'。它只能在网页上显示时使用。 – Barmar

+0

这可能是问题吗?另外,你的意思是这样的:'$ output-> addHTML(htmlspecialchars($ outP),ENT_QUOTES,'UTF-8'));'? – Muki

+0

我认为这与问题没有任何关系,只是一般性建议。 – Barmar

回答

1

我不确定是哪个数据库库,但可能调用select()会返回一个迭代器。

if (count($res) == 0) { 
    // update  
} 
+0

https://doc.wikimedia.org/mediawiki-core/master/php/classDatabaseBase.html#a76f9e6cb7b145a3d9020baebf94b499e它看起来像它返回布尔? – Muki

+0

@Muki它说:_如果查询没有返回任何行,则返回一个没有行的ResultWrapper。如果发生错误并且设置了_ignore errors_选项,它只会返回'false'。 – Barmar

1

我设法解决了这个问题,您需要输入以下内容if ($res->numRows())

0

而不是按照建议计数$ res中的行,您也可以使用selectRow()而不是select()。 selectRow将返回(第一个)匹配的行,如果没有则返回false。

0

只需使用upsert();这将在单个查询中执行选择/插入/更新组合。 PHP代码看起来会更简单,操作将会是atomic,这会让您省去所有令人讨厌的竞争条件错误。