php mysql相似度,mysql php选择一条与另一个相似的记录

作者探讨了如何在SQL中编写一个语句,以便在'HOMBRE_MUJER'、'CATEGORIA'和'NOMBRE'字段同时匹配两个字符串关键词。原始代码在搜索'hombres'和'hombres y mujeres'时遇到问题。优化后的函数使用了逻辑运算符和参数化查询来提高搜索准确性。
摘要由CSDN通过智能技术生成

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

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:

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 "

Productos encontrados

";

foreach($arrayProductos as $fila){

echo $fila['NOMBRE'] . " " . $fila['HOMBRE_MUJER'] . "
";

}

}else{

echo "

No results found " . $_GET['buscar'] . "";

}

}

?>

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.

解决方案

try this:

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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值