开发者

search using pdo, mysql and php

i'm trying my hand with PDO and would like to know if the following is the correct code to search keywords since it's giving me an error: mysql_real_escape_string(): [2002] A connection attempt failed because connected host has failed to respond.

php class:

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!";
                         }
           开发者_StackOverflow           $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 page:

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

else
   $quotes->displayQuotes();

displayQuotes() displays the quotes fine, so I'm assuming nothing is wrong with the connection in itself.


With PDO and binding params / prepared statements you do not need to escape strings. How you have it setup, PDO should automatically escape it for you.

Since you are using PDO, you are not using the mysql_connect driver and thus you cannot use the real_escape_string function as it requires a valid connection to the mysql server, using the mysql_connect.

EDIT:

Not sure about this if statement, but it could be problematic:

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

Would be better to use imo. It may or may not be the problem. The other issue is you should be checking the error information and alert yourself if there is an error in some way.


You don't have to use mysql_real_escape_string() in case you're using PDO prepared statements

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜