Searching for multiple script keywords requires some expert input

I used a keyword search script based on this tutorial: http://www.hackosis.com/2007/11/06/howto-simple-search-engine-with-php-and-mysql/

Like some of the commenters mentioned, the script ends up returning results based on the last word in search terms. So I also tried to implement one of the suggestions from another user, but now it seems to me that I am only getting results based on the first search query.

The code for my script can be found here: http://php.pastebin.com/m7759afd3

My print_r for results looks like this:

SELECT * FROM blog WHERE blog_title LIKE '%barry%' OR blog_content LIKE '%barry%' AND blog_title LIKE '%child%' OR blog_content LIKE '%child%' AND blog_title LIKE '%help%' OR blog_content LIKE '%help%' ORDER BY blog_title

SELECT * FROM links WHERE link_title LIKE '%barry%' OR link_desc LIKE '%barry%' AND link_title LIKE '%child%' OR link_desc LIKE '%child%' AND link_title LIKE '%help%' OR link_desc LIKE '%help%' ORDER BY link_title

SELECT * FROM pages WHERE page_title LIKE '%barry%' OR page_content LIKE '%barry%' AND page_title LIKE '%child%' OR page_content LIKE '%child%' AND page_title LIKE '%help%' OR page_content LIKE '%help%' ORDER BY page_title

      

Thank you for any help you could offer.

0


source to share


2 answers


If you want to return results containing any of the keywords , replace all ANDs with ORs .

If you do this, your db will check if any of the keywords exist in any column of the table.

Hence your final request will be read by the DB server as follows:



SELECT * FROM blog WHERE blog_title LIKE '%barry%' OR blog_content LIKE '%barry%' OR blog_title LIKE '%child%' OR blog_content LIKE '%child%' OR blog_title LIKE '%help%' OR blog_content LIKE '%help%' ORDER BY blog_title

      

and should return all records that have keywords (barry, child, help) in any column ( blog_title, blog_content

).

Hope it helps.

+3


source


The AND operator has higher precedence than OR, so if you want to return results containing all keywords , you need to add parentheses like this:



  SELECT * FROM blog
  WHERE (blog_title LIKE '%barry%' OR blog_content LIKE '%barry%')
    AND (blog_title LIKE '%child%' OR blog_content LIKE '%child%')
    AND (blog_title LIKE '%help%' OR blog_content LIKE '%help%')
  ORDER BY blog_title

      

+1


source







All Articles