I have some search functionality which allows a user to either select a name from a drop down list or type a persons name or part of it (wildcard functionality) into a search field.
The problem I am having is that if the drop down option is used then the search field won’t be and vice versa.
I have tried some SQL as follows (please note the variables represent data sent in via a form):
SELECT id, name, age FROM player
WHERE player.id = '$id'
OR player.name LIKE '%$text%'
When the above is used the wildcard functionality works fine.
However if you select a player from the drop down then it returns all players. This is because the value for $text is nothing (empty) and LIKE ‘%%’ means select everything and hence it selects all names.
I then tried the following:
SELECT id, name, age FROM player
WHERE player.id = '$id'
AND player.name LIKE '%$text%'
Now the drop down functionality works as expected but wild card searches do not work. This is because I assume that AND requires both statements to be true and because $id is nothing (empty) when just a wildcard entry is specified, the condition is never true.
Can anyone help me with some sql to ensure that both the dropdown and the wildcard search work in isolation of each other?
Thanks for your time and help in advance.
1 Answer