数组内的SQL LIKE% [英] SQL LIKE % inside array

查看:184
本文介绍了数组内的SQL LIKE%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know how to perform an SQL LIKE % query for a single value like so:

SELECT * FROM users WHERE name LIKE %tom%;

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

but how do I do this if the search terms for my LIKE comes from an array? For example, let's say we have an array like this:

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

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

How do I perform my SQL LIKE % to search for the words in my array like:

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

没有将整个查询放入foreach循环之内

WITHOUT putting the whole query inside a foreach loop or something

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

EDIT : I forgot to mention that I'm doing this in cakePHP inside the conditions of the cakePHP find('all') method, so that complicates things a little bit.

谢谢

推荐答案

$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的代码:


code for 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

这篇关于数组内的SQL LIKE%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆