2015-06-25 75 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,這會讓您省去所有令人討厭的競爭條件錯誤。