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

后端 未结 1 1132
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 16:44

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 st         


        
相关标签:
1条回答
  • 2020-11-28 17:38

    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->bindParam($key+1, '%'.$keyword.'%');
      }
      $sql->execute ();
    
    0 讨论(0)
提交回复
热议问题