Greetings companions, I want to know how I can do a search with more than one word in the imput, for example:
Let me take these two words and make the query so that I can return results where those two words are found.
You need to generate a query sql like this
SELECT * FROM tu_tabla WHERE nombre like '%palabra1%' OR nombre like '%palabra2%'
To do this you must separate the words that make up your phrase, in php is done with explode
$palabras=explode (' ','tu cadena original');
then you generate your query by iterating through the words
$query='SELECT * FROM tu_tabla WHERE';
for ($i=0;$i<count($palabras);$i++){
$query.=" nombre like '%".$palabras[$i]."%' ";
if ($i<count($palabras)-1){
$query.=" or ";
}
}
I suggest you delete the short and commonly used words like 'the' or 'of'
here is a function of php that performs the search for more than one word, it is proven in mysql The result of the string that it gives you only has to add it to the query that you have always formed after where Ex.
@param $campo -> array con el nombre de los campos de las tablas.
@param $value -> string con el valor de que se le va colocar al campo de la base de datos.
//Función para el filtro SQL.
if(!function_exists('get_search')){
function get_search($campo, $value){
if(isset($campo) AND isset($value)){
//Pasamos el valor de string a array.
$value = trim($value);
$value_array = explode(" ",$value);
$count = count($campo);
$c = 1;
foreach($value_array as $value){
if($count == 1){
$query .= $campo[0]." LIKE '%".$value."%'";
}else{
for($i = 0; $i< $count ; $i++){
if($count == $i+1){
$query .= " OR ".$campo[$i]." LIKE '%".$value."%')";
}elseif($i == 0){
if($c == 1){
$query .= " AND ((";
}else{
$query .= " OR (";
}
$query .= " ".$campo[$i]." LIKE '%".$value."%'";
}else{
$query .= " OR ".$campo[$i]." LIKE '%".$value."%'";
}
}
}
$c++;
}
$query .= " )";
return $query;
}else{
return NULL;
}
}
}
How to use it:
$campo = array('nombre','nombre');
$value = 'casa negra';
$seg_query = get_search($campo,$value);
$query = "Select * From nombre_tabla Where 1 ".$seg_query."";