mysql php选择一个与另一个类似的记录

时间:2017-03-02 04:02:11

标签: php mysql sql

我知道这似乎是一个重复的,没有堆栈溢出等问题,但我们走了。

我试图制作一个可以在两个字符串之间找到巧合的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个值:&#34; hombres&#34;和#34; mujeres&#34;,如果我搜索hombres我得到所有有hombres CATEGORIA的记录但是当我搜索hombres y mujeres我没有得到任何结果时,我尝试使用我读过的不同句子但我没有&没有运气,我希望你能帮助我解决这个问题,从而大大拯救我。

1 个答案:

答案 0 :(得分: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;
}