Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

two words and blank spaces not working in MYSQL query using LIKE

i'm making a searcher for my site and this works fine with one word querys

 $consulta = mysql_query("SELECT * FROM recetas WHERE (titulo LIKE '%$busqueda%' OR intro LIKE '%$busqueda%' OR extra LIKE '%$busqueda%') ORDER BY id DESC");

But if i type 'two words' it doesn't give me result, $busqueda it's result from a <input/> given through $_POST['TERM']

any idea what i'm missing?

SOLVED

i was missing to encode the variable to URI... oops haha THANKS!

Upvotes: 0

Views: 8224

Answers (3)

where ( MATCH( titulo, intro, extra) AGAINST ('word1 word2' in BOOLEAN MODE))

Upvotes: -2

Mark Wilkins
Mark Wilkins

Reputation: 41232

Unless the two words are adjacent in the text, the LIKE operator won't find them. You may want to use full text search.

In order to find two non-contiguous words, the input would need to be split up into two separate values and the query would have to look something like this:

WHERE (titulo LIKE '%$word1%' OR intro LIKE '%$word1%' OR extra LIKE '%$word1%' OR
       titulo LIKE '%$word2%' OR intro LIKE '%$word2%' OR extra LIKE '%$word2%' )

That is assuming you want a match with either word. If both must match, then something like this:

WHERE (titulo LIKE '%$word1%' AND titulo like '%$word2%' OR
       intro LIKE '%$word1%' AND intro LIKE '%$word2%'  OR 
       extra LIKE '%$word1%' AND extra LIKE '%$word2%' )

And one other thing. It would be better to use parameterized queries to avoid an SQL injection.

Upvotes: 2

Marc B
Marc B

Reputation: 360572

Think of how your query will look at the end:

Select ... where '%two words%. ...

If you want to search for words like that, you'll have to massage the data to look more like:

 ... Like '%two%words%'
 ... Like '%two%' or like '%words%'

depending on your exact search requirements

Upvotes: 3

Related Questions