Search for each word in different columns in the same table with one query
I have string
:
$searchkey="a b c";
I have three columns:
$column=array('column1','column2','column3');
I want to check every word in this column and get one query row. To get it I did the following ... but it doesn't look the way I want it ... I am very new to PHP so I am a stack. Can you help solve this or any other easy way to get a single query string?
$searchkey="a b c";
$words = EXPLODE(" ",$searchkey);
$column=array('column1','column2','column3');
foreach($column as $column){
for($i=0; $i<count($words); $i++){
$string1.=''.$column.' like %'.$words[$i].'% or ';
}
$string1 = SUBSTR($string1,0,STRLEN($string1)-4);
$string2.= '('.$string1.') or ';
}
echo $string2= SUBSTR($string2,0,STRLEN($string2)-4);
This gives me:
(column 1 like% a% or column 1 like% b% or column 1 like% c%) or (column1 like% a% or column1 like% b% or column 1 like% c% column2 like% a% or column2 like% b% or column2 like% c%) or (column 1 like% a% or column1 like% b% or column 1 like% c% column2 like% a % or column2 like% b% or column2 like% c% column3 like% a% or column3 like% b% or column3 like% C%)
However, I would like to get:
(column 1, such as% a% or column 1, such as% b%, or column 1, such as% c%) or (column2, such as% a%, or column2, such as% b%, or column2, such as% c%) or (column 3 like% a% or column3 like% b% or column3 like% c%)
Thanks in advance.
source to share
You just need to add the statement $string1 = "";
as the first statement in the body of the loop foreach
, before resetting on every iteration, rather than adding to it every time!
...
foreach($column as $column) {
$string1 = ""; // <-- Add this line, and every thing will be fine :)
for($i=0; $i<count($words); $i++) {
$string1.=''.$column.' like %'.$words[$i].'% or ';
}
...
source to share