3

I am trying to set up a search feature on my site that will only return exact matches to keyword entered by the user. So if the user searches "dog" I don't want an article titled "Doggy Style" to appear in the search results (just an example I don't really have an article by that name). This of course does exactly that:

SELECT * FROM articles WHERE article_title LIKE '%$searchQuery%'

$searchQuery here is a PHP variable taken from the user's input form. So is there any way to return only exact matches?

3
  • How do you define "exact" matches, case-sensitive and space-separated (e.g. "the dog walked" but not "doggy biscuit" or "Dog Eat Dog World")? Commented Mar 21, 2010 at 3:00
  • 1
    why you are not using Full text Search ? dev.mysql.com/doc/refman/5.0/en/fulltext-search.html Commented Mar 21, 2010 at 3:00
  • @ drorhan I will look into it, seems interesting. Commented Mar 21, 2010 at 3:05

4 Answers 4

4
SELECT * FROM articles WHERE article_title = '$searchQuery'

would return an exact match. Notice the change from 'like' to '=' and notice the % signs have been removed.

Also be sure never to use direct input from a user form as input to search your MySQL database as it is not safe.

Sign up to request clarification or add additional context in comments.

Comments

1

For exact matches you can do:

SELECT * FROM articles WHERE article_title = '$searchQuery'

In MySql nonbinary string comparisons are case insensitive by default.

Comments

1
SELECT * FROM articles WHERE article_title = '$searchQuery'

Comments

-1

I think you should do like this, it works perfect.

SELECT * FROM articles WHERE article_title='$searchQuery'

execute(array('%'.$searchQuery.'%'))

1 Comment

What does this add 7 years later which other answers don't provide?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.