我想要我的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> " . $cQuote . " </q></p><br />"
. "<p id=\"s_author\"><b>-</b> " . $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()顯示細膩的報價,所以我假設沒有什麼是錯在自己的連接。
感謝指出了這一點。那裏有任何其他的錯誤,因爲它表示「沒有找到結果」,即使這個關鍵字有引號。 – input 2010-07-27 18:30:02
那麼,like語句中的額外空格將只能找到搜索字符串,如果它被空格包圍(不確定這是否是有意的)。但我很少使用bindparam方法,所以我不能100%確定該功能。查詢看起來沒問題,因爲這些空間是有意的。儘管如此,如果搜索關鍵字處於開頭或結尾,它將不匹配,因爲它需要空格匹配它。 – 2010-07-27 18:32:56
那麼你會用什麼來代替bindparam來搜索關鍵字?因爲我是PDO新手,我還在學習。所以如果你有一個有效的或更好的選擇,請指出。 – input 2010-07-27 18:36:56