dsa1234569 2014-07-18 23:59
浏览 55

如何使用数组中的多个关键字在mysql表中搜索列?

I am trying to make a search function for my database that refines the search with each additional keyword.

I don't want to limit it to a fixed number of keywords so I use a foreach() loop to extend the sql by another AND column LIKE ? for each keyword.

However the array-binder loop produces different results than using other methods that should do the exact same thing.

My table contains 1 column and 3 rows : "a b c", "b c", "1 2 3".

$Keywords = array("a","b","c"); //those search keywords should only apply to the first row
$sql = "SELECT * FROM table WHERE column LIKE ?";

foreach ($Keywords as $Keyword) {

    if ($count > 0) {       
        $sql = $sql . "AND column LIKE ?";
    }
    $count = $count + 1;
}
$query = $con->prepare($sql);

//loop to bind parameters
foreach ($Keywords as $n=>$Keyword) {
    $Keyword = "%".$Keyword."%";                                
    $query->bindParam($n+1,$Keyword,PDO::PARAM_STR);
}
$query->execute;

This will return the rows a b c and b c although it should only return the row that contains all 3 strings: a , b and c.

If I don't use a loop to bind the parameters (which limits the number of keywords) it does what is is supposed to and only shows "a b c".

        $a = "%a%";
        $b = "%b%";
        $c = "%c%";
        $query->bindParam(1,$a,PDO::PARAM_STR);
        $query->bindParam(2,$b,PDO::PARAM_STR);
        $query->bindParam(3,$c,PDO::PARAM_STR);

It also works If I just execute this :

$sql = "SELECT * FROM table WHERE column LIKE '%a%' AND column LIKE '%b%' AND column LIKE '%c%'";
  • 写回答

1条回答 默认 最新

  • dongwei1954 2014-07-19 00:30
    关注

    The working examples use the % wildcard but your looped values don't.

    Change

    $Keywords = array("a","b","c");
    

    to

    $Keywords = array("%a%","%b%","%c%");
    

    or another solution is to add the wildcards in the bindParam call

    foreach ($Keywords as $n=>$Keyword) {                               
       $query->bindParam($n+1,"%$Keyword%",PDO::PARAM_STR);
    }
    

    Another potential issue is that your constructed query doesn't have a space between ? and AND i.e.

    SELECT * FROM table WHERE column LIKE ?AND column LIKE ?AND column LIKE ?
    

    Although I'm not sure if a missing space after the ? is illegal, I recommend padding your AND condition with spaces

    $sql = $sql . " AND column LIKE ? ";
                   ^                 ^
    
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图