2010-07-27 94 views
1

我想要我的PDO的手,想知道如果下面是正確的代碼搜索的關鍵字,因爲它給我一個錯誤:mysql_real_escape_string(): [2002] A connection attempt failed because connected host has failed to respond.搜索使用PDO,MySQL和PHP

PHP類:

public function searchQuotes() 
     { 
      $search = mysql_real_escape_string($_POST['search']); 

      $sql = "SELECT cQuotes, vAuthor, cArabic, vReference FROM thquotes WHERE cQuotes LIKE '% :search %' ORDER BY idQuotes DESC"; 


        try { 

         $query = $this->_db->prepare($sql); 
         $query->bindParam(':search', $search, PDO::PARAM_STR); 
         $query->execute(); 

         if(!$query->rowCount()==0) 
         { 
           while($row = $query->fetch()) 
         { 
          echo $this->formatSearch($row); 
         } 


         } 
         else 
         { 
          echo "No results found!"; 
         } 
         $query->closeCursor(); 
        } 
        catch (Exception $ex){ 

         echo "Something went wrong " . $ex; 
        } 
     } 

     public function formatSearch($row) 
     { 
      $cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search); 

      return "<p id=\"s_arabic\">" . $this->h($row['cArabic']) . "</p><br />" 
      . "<p id=\"s_quotes\"><q>&nbsp;" . $cQuote . "&nbsp;</q></p><br />" 
      . "<p id=\"s_author\"><b>-</b>&nbsp;" . $this->h($row['vAuthor']) . "</p><br />" 
      . "<p id=\"s_reference\"><span class=\"source\">Source:</span> " . $this->h($row['vReference']) . "</p>"; 
     } 

PHP頁面:

if (isset($_POST['search'])) 
    $quotes->searchQuotes(); 

else 
    $quotes->displayQuotes(); 

displayQuotes()顯示細膩的報價,所以我假設沒有什麼是錯在自己的連接。

回答

3

使用PDO和綁定參數/準備語句,您不需要轉義字符串。你如何設置它,PDO應該自動爲你自動轉義它。

由於您使用的是PDO,因此您不使用mysql_connect驅動程序,因此無法使用real_escape_string函數,因爲它需要使用mysql_connect與mysql服務器進行有效連接。

編輯:

if語句,不知道這一點,但它可能是有問題的:

if($query->rowCount()>0)

會更好海事組織使用。這可能是也可能不是問題。另一個問題是你應該檢查error information並以某種方式提醒自己是否有錯誤。

+0

感謝指出了這一點。那裏有任何其他的錯誤,因爲它表示「沒有找到結果」,即使這個關鍵字有引號。 – input 2010-07-27 18:30:02

+0

那麼,like語句中的額外空格將只能找到搜索字符串,如果它被空格包圍(不確定這是否是有意的)。但我很少使用bindparam方法,所以我不能100%確定該功能。查詢看起來沒問題,因爲這些空間是有意的。儘管如此,如果搜索關鍵字處於開頭或結尾,它將不匹配,因爲它需要空格匹配它。 – 2010-07-27 18:32:56

+0

那麼你會用什麼來代替bindparam來搜索關鍵字?因爲我是PDO新手,我還在學習。所以如果你有一個有效的或更好的選擇,請指出。 – input 2010-07-27 18:36:56

1

您沒有使用的情況下,mysql_real_escape_string()你使用PDO預處理語句