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 th
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%';
$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
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';
try using REGEXP
SELECT * FROM users where fieldName REGEXP 'Tom|Smith|Larry';
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 );
}
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.