使用implode函数调整php mysql搜索查询

时间:2014-07-16 06:04:23

标签: php mysql sql arrays

我正在搜索框中的任何用户类型执行一个PHP mysql搜索查询与implode函数。查询工作正常,但我想稍微改变它,因为它没有给我正确的结果。请看看查询

$lcSearchVal=$_GET['name'];
$lcSearcharr=explode("-",$lcSearchVal);
foreach( $lcSearcharr as $lcSearchWord ){
$lcSearchWord = mysqli_real_escape_string($mysqli, $lcSearchWord);
$lcSearchWord = preg_replace('/%/', '\%', $lcSearchWord);
    $parts[] = '`Description` LIKE "% '.$lcSearchWord.'%"';
    $parts1[] = '`Description` LIKE "% '.$lcSearchWord.' %"';
}

$qry='SELECT * FROM table_name WHERE  ('.implode ('AND',$parts).')';

首先,我在第二页的搜索框中输入搜索内容从上面代码的第一行开始搜索。然后我通过在搜索中用连字符拆分它们将该变量拆分成数组。然后我执行一个foreach循环数组,用于sql查询

例如: - 用户在第一页搜索as-men休闲鞋。 我会在像男士休闲鞋这样的第二页​​中得到它。 然后我会将它们放在一个像三个元素一样的阵列中,如男士,休闲鞋,鞋子。 然后我将执行上面写的搜索查询,其形式如下

select * from table_name where (Description like '%men %' and Description like '%casual %' and Description like '%shoes %')

但我希望查询看起来如下

select * from table_name where (Description like '%men %' and Description like '%casual %') or (Description like '%casual %' and Description like '%shoes %') or (Description like '%men %' and Description like '%shoes %')

请帮助调整查询

1 个答案:

答案 0 :(得分:0)

使用2个for循环枚举所有组合:

<?php
$s = "men-casual-shoes";
$ss = explode('-', $s);
$parts = array();
for ($i = 0; $i < count($ss)-1; $i++) {
    for ($j = $i+1; $j < count($ss); $j++) {
        # You may want to do mysqli_real_escape_string here
        $w1 = str_replace('%', '\%', $ss[$i]);
        $w2 = str_replace('%', '\%', $ss[$j]);
        $parts[] = "(`description` like '% $w1 %' and `description` like '% $w2 %')";
    }
}

$qry = 'SELECT * FROM table_name WHERE  ('.implode (' or ',$parts).')';
echo $qry;

打印

SELECT * FROM table_name WHERE  ((`description` like '% men %' and `description` like '% casual %') or (`description` like '% men %' and `description` like '% shoes %') or (`description` like '% casual %' and `description` like '% shoes %'))