I am building a search box that queries a database and autofills suggestions below.
I want to be able to priorities the results in order of :
1 – Exact match
2 – Starts with the same couple of letters
3 – Contains the string somewhere within the database
I have a SQL statement
SELECT *
FROM Products
WHERE ProductName LIKE ?
OR ProductName LIKE ?
GROUP BY ProductName
ORDER BY ProductName ASC
LIMIT 10
In an example for searching for the word “computer”
When typing “co” it should show
- co -co
- co mputer
- co mputer desk
- ac co unt
but when furthering the search to “computer”
- computer
- computer deks
The first binding param contains %computer% and the second contains c%omputer%
Thanks for the help and if you need anything clarifying let me know.
This works well, The first ? holds ‘co’ the second ? holds ‘co%’ and the third ? holds ‘%co%’
This prioritises the exact match first, then starting with the string and then containing the string.