SQL LIKE % inside array

2019-01-14 02:23发布

问题:

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

SELECT * FROM users WHERE name LIKE %tom%;

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");

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]%

WITHOUT putting the whole query inside a foreach loop or something

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.

Thanks

回答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);

Edit: code for CakePHP:

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

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

Read up on this stuff: http://book.cakephp.org/1.3/en/view/1030/Complex-Find-Conditions



回答2:

In case of standard SQL, it would be:

SELECT * FROM users WHERE name LIKE '%tom%' 
                       OR name LIKE '%smith%' 
                       OR name LIKE '%larry%';

Since you're using MySQL you can use RLIKE (a.k.a. REGEXP)

SELECT * FROM users WHERE name RLIKE 'tom|smith|larry';


回答3:

You can't. It'll have to be a chained field like %..% or field like %..% or .... A where ... in clause only does extract string matches, with no support for wildcards.



回答4:

try using REGEXP

SELECT * FROM users where fieldName REGEXP 'Tom|Smith|Larry';


回答5:

i just took the code of 472084.

$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);

For my self, i had to modify it because it's returned me an error SQL. I Post it for people who gonna read the thread.

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

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

The difference between them is about quote, my mysql DB said there is a problem ! so i had to escape quote from $sql[] = 'name LIKE %'.$word.'%' and now it's work perfectly.



回答6:

Blockquote

/** * Implode a multidimensional array of values, grouping characters when different with "[]" block. * @param array $array The array to implode * @return string The imploded array */ function hoArray2SqlLike( $array ) { if ( ! is_array( $array ) ) return $array;

$values  = array();
$strings = array();

foreach ( $array as $value )
{
    foreach ( str_split( $value ) as $key => $char )
    {
        if ( ! is_array( $values[ $key ] ) )
        {
            if ( isset( $values[ $key ] ) )
            {
                if ( $values[ $key ] != $char )
                {
                    $values[ $key ]     = array( $values[ $key ] );
                    $values[ $key ][]   = $char;
                }
            }
            else
                $values[ $key ] = $char;
        }
        elseif ( ! array_search( $char , $values[ $key ] ) )
            $values[ $key ][] = $char;
    }
}

foreach ( $values as $value )
{
    if ( is_array( $value ) )
        $value = '['.implode( '', $value ).']';

    $strings[] = $value;
}

return implode( '', $strings );

}



回答7:

In this code we can't get double quotes in sql query

$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);

SELECT * FROM person where name like %"Tom"% OR name like %"Smith"% OR name like %"Larry"%;
// error in double quotes and % is out side of Double quotes .

Or you can also use comma separated value:-

$name = array(Tom, Smith, Larry);

$sql="SELECT * FROM person";

    extract($_POST);
    if ($name!=NULL){
    $exp_arr= array_map('trim', explode(",",$name));
    echo var_export($exp_arr);
    //die;
        foreach($exp_arr as $val){
        $arr = "'%{$val}%'";
        $new_arr[] = 'name like '.$arr;
        }

      $new_arr = implode(" OR ", $new_arr);
      echo $sql.=" where ".$new_arr;
    }
        else {$sql.="";}

Echo sql query like this:-

SELECT * FROM person where name like '%Tom%' OR name like '%Smith%' OR name like '%Larry%';