简体   繁体   中英

How to search a MySQL database for a specific string

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?

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.

For exact matches you can do:

SELECT * FROM articles WHERE article_title = '$searchQuery'

In MySql nonbinary string comparisons are case insensitive by default.

SELECT * FROM articles WHERE article_title = '$searchQuery'

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

SELECT * FROM articles WHERE article_title='$searchQuery'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM