I am creating a search filter feature and will be sending the filter information via the URL. The issue I am facing is that since it’s a filter, some of the information will be there at some times, and some not. This creates the undefined variable problem.
The maximum amount of filters will be like so: search.php? cat=Computers&credits1=1&credits2=2&rev=5&stars=5. I will also be pulling data from multiple SQL tables based on the GET variables set.
How can I account for some variables being unset at certain times in order to run my query? I think I could do this via a bunch of if else statements accounting for each case, but that seems like “dirty code.”
You should just build your SQL statement dynamically based on the filter values that are passed. This will likely mean conditionals, but this is really the best method in order to optimize your queries on the database.
It might look something like this (example uses mysqli, but this should be similar for any sort of DB library using prepared statements):