I'm trying to create a dynamic search query, based on the user input.
Requirements:
- A user could fill in none, some, or all fields.
- The query searches in a table for a record that matches all the requirements.
Now I have done my research, and I found out multiple ways on doing this. But none of them work, and if they do, they are far from practical.
Attempt:
At the moment I'm creating a query like this:
SELECT *
FROM assignments
WHERE (id = $id OR id = '')
AND (field1 = $field1 OR field1 = '')
This query works, but only if you fill in all the fields.
I got this from a stackoverflow article, that I can't find anymore, that said:
If the user has filled in an input field it will check the first rule "id = $input" and if the user hasn't specified any input it will check for "id = '' " and when it checks for that, it will just return everything. Because it escapes the empty search rule.
But as you might already know, it doesnt work..
How would you suggest me to approach this?