I’m own a wallpaper website and I’m trying to write a search feature that will search the database for the terms the user is searching for. I have 2 fields in the database I’m searching against TAGS and NAME
The current way I’m doing it is I take the search term divide it up into multiple words and then search the database using those terms. So if a user searches for “New York” my query will look like this
SELECT * FROM wallpapers
WHERE tags LIKE '%New%' OR name LIKE '%new%'
or tags LIKE '%York%' OR name LIKE '%York%'
The issue with that of course is that anything with the term new in it will be pulled up also like say “new car” etc. If I replace the query above with the following code then it’s too vague and only like 2 wallpapers will show up
SELECT * FROM wallpapers
WHERE tags LIKE '%New York%' OR name LIKE '%New York%'
Does anyone have a better way to write a search query?
Looks like you want to introduce the concept of relevance.
Try:
By the way, this will perform very, very poorly if your database grows too large – you want to be formatting your columns consistently so they’re all upper case (or all lower case), and you want to avoid wildcards in your where clauses if you possibly can.
Once this becomes a problem, look at full text searching.