本文介绍了mysql php选择一条与另一个相似的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know this may seem like a duplicated, out of stackoverflow, etc question but here we go.

我正在尝试创建一个SQL语句,该语句可以找到两个字符串之间的巧合

I'm trying to make an SQL sentence that can find a coincidence between two strings

        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",如果我搜索同名杂物,我将获得所有具有CATEGORIA同名杂物的记录,但是当我搜索同种异物y时毫无疑问,我没有结果,我尝试使用阅读过的不同句子,但是我没有任何运气,希望您可以通过帮助我解决此问题来极大地节省我.

Everything works fine, In my database I store only 2 values in CATEGORIA which are: "hombres" and "mujeres", if i search for hombres I get all records which have a CATEGORIA of hombres but when i search for hombres y mujeres I get no results, I have tried using different sentences that i read but I haven't had any luck, I hope you can greatly save me by helping me solve this problem.

推荐答案

尝试一下:

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

这篇关于mysql php选择一条与另一个相似的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 15:54