我知道这似乎是重复的,出于stackoverflow等问题,但是我们开始了。

我正在尝试使一个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>";
                }
            }
        ?>


一切正常,在我的数据库中,我仅在CATEGORIA中存储2个值:“ hombres”和“ mujeres”,如果我搜索hombres,我将获得所有包含CATEGORIA hombres的记录,但是当我搜索hombres y mujeres时,我会得到没有结果,我尝试使用阅读过的不同句子,但我没有任何运气,希望您可以通过帮助我解决此问题而大大节省我的时间。

最佳答案

尝试这个:

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;
}

10-05 17:52