Jeffro Posted April 28, 2012 Share Posted April 28, 2012 $find is the search my user types in a form. In searching mysql I want to search inventory.title and inventory.description ... and I want to return all results that have $find in either the title or description. I tried this: select * from inventory WHERE title LIKE '%$find%' or description LIKE '%$find%'"; That works for single words but if the user types in 2 words, I need it to look in title and description for any combination. Example: My user might type: miami truck I need to then perform a search where miami might only be in the title and truck might only be in the description. Quote Link to comment Share on other sites More sharing options...
Jeffro Posted April 28, 2012 Author Share Posted April 28, 2012 Looking some more, I guess maybe I should post in the php forum? I'm guessing I need to somehow break $find into an array and then search each individual word? Quote Link to comment Share on other sites More sharing options...
awjudd Posted April 28, 2012 Share Posted April 28, 2012 Split the word on the space then add the LIKE for each one. ~awjudd Quote Link to comment Share on other sites More sharing options...
Jeffro Posted April 28, 2012 Author Share Posted April 28, 2012 Split the word on the space then add the LIKE for each one. ~awjudd Since I don't know how many words they will use in the search, I would create an array, I guess? If so.. How do I then use that to search? Quote Link to comment Share on other sites More sharing options...
awjudd Posted April 28, 2012 Share Posted April 28, 2012 You build the query dynamically. $words=explode(' ', 'foo bar'); $query='SELECT * FROM inventory '; $combine=' WHERE '; foreach($words as $word) { $query .= $combine . " ( title LIKE '%" . $word . "%' or description LIKE '%" . $word . "%' )"; $combine=' AND '; } echo $query; ~awjudd Quote Link to comment Share on other sites More sharing options...
Jeffro Posted April 29, 2012 Author Share Posted April 29, 2012 You build the query dynamically. $words=explode(' ', 'foo bar'); $query='SELECT * FROM inventory '; $combine=' WHERE '; foreach($words as $word) { $query .= $combine . " ( title LIKE '%" . $word . "%' or description LIKE '%" . $word . "%' )"; $combine=' AND '; } echo $query; ~awjudd Glad you hooked me up with that because I had to study it about 10 minutes to figure out what you were doing! It finally made sense and I stuck it in my script.. and voila! Works perfectly. Thanks so much. Really appreciate it. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.