Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

php - LIKE query using multiple keywords from search field using PDO prepared statement

Site users use a search form to query a database of products. The keywords entered search the titles for the products in the database.

    public function startSearch($keywords){
        $keywords = preg_split('/[s]+/', $keywords);
        $totalKeywords = count($keywords);

        foreach($keywords as $key => $keyword){
            $search .= '%'.$keyword.'%';
            if($key != ($totalKeywords)-1){
                $search .= ' AND itemTitle LIKE ';
            }
        }
$sql=$this->db->prepare("SELECT * FROM prodsTable WHERE itemTitle LIKE ?");
$sql->bindParam(1, $search);        
$sql->execute ();
$sql->fetchALL(PDO::FETCH_ASSOC);

The search works if a user enters a single keyword, but if multiple keywords are used the query does not execute.

if: $keywords = 'apple ipod'; $search = '%apple% AND itemTitle LIKE %ipod%';

So the prepared statement should look like this:

"SELECT * FROM prodsTable WHERE itemTitle LIKE %apple% AND itemTitle LIKE %ipod%"

No results return when two products should return having both "apple" and "ipod" in their titles.

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Prepared statements protect you from sql injection, so sql code in the parameters will not be interpreted. You will have to build a sql query with the correct number of AND itemTitle LIKE ? before calling prepare().

  $keywords = preg_split('/[s]+/', $keywords);
  $totalKeywords = count($keywords);
  $query = "SELECT * FROM prodsTable WHERE itemTitle LIKE ?";

  for($i=1 ; $i < $totalKeywords; $i++){
    $query .= " AND itemTitle LIKE ? ";
  }

  $sql=$this->db->prepare($query);
  foreach($keywords as $key => $keyword){
    $sql->bindValue($key+1, '%'.$keyword.'%');
  }
  $sql->execute ();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...