2017-03-02 47 views
1

我知道這可能看起來像一個重複的,出了stackoverflow等問題,但在這裏,我們走了。mysql php選擇類似於另一個的記錄

我試圖做一個SQL語句,可以找到兩個字符串之間的巧合

 function getProductos($keyWords){ 
      $keyWords = addslashes(strtolower($keyWords)); 
      $keyWordsExploded = explode(" ",$keyWords); 
      $sql = "SELECT * FROM PRODUCTOS WHERE HOMBRE_MUJER LIKE :keyWords OR CATEGORIA LIKE :keyWords" OR NOMBRE LIKE :keyWords; 

      $query = self::$conn->prepare($sql); 
      $query->execute(array(":keyWords"=> "%" . $keyWords . "%")); 

     return $query; 
     } 

In other part of the page I have this code: 
      <?php 
      if(isset($_GET['buscar'])){ 
       require(PAGES_DIR . "queries_products.php"); 
       $consultaProducts = new QueryProductos(); 
       $productos = $consultaProducts->getProductos($_GET['buscar']); 

       if($productos->rowCount()!=0){ 
        $arrayProductos = $productos->fetchAll(PDO::FETCH_ASSOC); 
        echo "<h3>Productos encontrados</h3>"; 
        foreach($arrayProductos as $fila){ 
         echo $fila['NOMBRE'] . " " . $fila['HOMBRE_MUJER'] . "<br>"; 
        } 
       }else{ 
        echo "<p class='alert alert-warning'>No results found <strong>" . $_GET['buscar'] . "</strong>"; 
       } 
      } 
     ?> 

一切工作正常,在我的數據庫我店只有2 CATEGORIA值分別是:「hombres」和「 mujeres「,如果我搜索hombres,我得到的所有記錄都有hombres的CATEGORIA,但是當我搜索hombres y mujeres時,我沒有得到任何結果,我嘗試過使用不同的句子,但我沒有運氣,希望你能幫助我解決這個問題,從而大大節省我。

+1

爲什麼你的發言結束前關閉了雙引號? –

回答

0

試試這個:

function getProductos($keyWords) { 

    $keyWordsExploded = explode(" ",$keyWords); 
     $sql = "SELECT * FROM PRODUCTOS WHERE "; 
     $likes = array("HOMBRE_MUJER", "CATEGORIA", "NOMBRE"); // build up our columns which will be used in our condition in sql statment 

     $params = array(); 
     // building up our sql statment and collecting our params 
     foreach($likes as $like) { 
     foreach($keyWordsExploded as $kw) { 
      $sql .="$like like ? or "; 
      $params[] = "%".$kw."%"; 
     } 
     } 

    $sql = rtrim($sql, "or "); // trim the last "or" condition in sql statment 

    $query = self::$conn->prepare($sql); 

    $query->execute($params); 

    return $query; 
} 
+0

非常非常好的男人。非常感謝你的幫助! C: –

+0

我很高興幫助你。 –