How to search for multiple terms in a field?

1

My scenario and the following, I have an input where the user places the term and clicks search

EX: car horizon [ENTER]

But you're listing the result of the separated words

EX: 3 results found

id1 - house in belo horizonte

id2 - accepts car in exchange

id3- car located in Belo Horizonte

I would like you to display only the result that contains the 2 words

EX: 1 result found

id1- car located in Belo Horizonte

?>
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING);
$palavras = explode(" ", $search_term);
for ($i = 0; $i < count($palavras); $i++) 
$q = "SELECT * FROM classificados WHERE texto LIKE '%".$palavras[$i]."%' AND aprovado='s' ORDER BY ID desc";
$r = mysql_query($q);
if(mysql_num_rows($r)==0)//no result found
{
echo "<div id='search-status'>Nenhum resultado encontrado!</div>";
}
else //result found
{
echo "<ul>";
while($row = mysql_fetch_assoc($r))
    {
    $title = $row['texto'];
?>

I hope to have well illustrated my doubt

    
asked by anonymous 10.10.2014 / 03:35

1 answer

4

Here's a modification to your query loop:

 $search_term = filter_var( $_GET['s'], FILTER_SANITIZE_STRING );
 $palavras = explode( ' ', $search_term );
 $q = 'SELECT * FROM classificados WHERE';
 for ( $i = 0; $i < count($palavras); $i++ ) { 
    $q .= " texto LIKE '%" . $palavras[$i] . "%' AND " ;
 }
 $q .= " aprovado='s' ORDER BY ID desc";
 $r = mysql_query( $q );

 if( mysql_num_rows( $r )==0 ...


If you prefer the exact search that does not get carros instead of carro , just use this:

 $search_term = filter_var( $_GET['s'], FILTER_SANITIZE_STRING );
 $palavras = explode( ' ', $search_term );
 $q = 'SELECT * FROM classificados WHERE';
 for ( $i = 0; $i < count( $palavras ); $i++ ) { 
    $q .= " CONCAT( \" \", texto, \" \" ) LIKE '% " . $palavras[$i] . " %' AND "; 
 }
 $q .= " aprovado='s' ORDER BY ID desc";
 $r = mysql_query($q);

Be careful in this case to keep the spaces as they are in the code.

    
10.10.2014 / 05:31