一尘不染

数组内的SQL LIKE%

mysql

我知道如何对单个值执行SQL LIKE%查询,如下所示:

SELECT * FROM users WHERE name LIKE %tom%;

但是,如果LIKE的搜索字词来自数组,该怎么办?例如,假设我们有一个像这样的数组:

$words = array("Tom", "Smith", "Larry");

如何执行我的SQL LIKE%来搜索数组中的单词,例如:

SELECT * FROM users WHERE name LIKE %[each_element_from_my_array]%

无需将整个查询放在foreach循环之内

编辑 :我忘了提到我在cakePHP find(’all’)方法的条件下在cakePHP中执行此操作,因此使事情变得有些复杂。

谢谢


阅读 1096

收藏
2020-05-17

共1个答案

一尘不染

$sql = array('0'); // Stop errors when $words is empty

foreach($words as $word){
    $sql[] = 'name LIKE %'.$word.'%'
}

$sql = 'SELECT * FROM users WHERE '.implode(" OR ", $sql);

编辑:CakePHP的代码:

foreach($words as $word){
    $sql[] = array('Model.name LIKE' => '%'.$word.'%');
}

$this->Model->find('all', array(
    'conditions' => array(
        'OR' => $sql
    )
));

阅读以下内容:http : //book.cakephp.org/1.3/en/view/1030/Complex-Find-
Conditions

2020-05-17