I’m writing a query that uses input from a search form where Brand, Type and Price are optional input fields:
SELECT * FROM `database` WHERE `brand` LIKE "%' . $brand . '%" AND `type` LIKE "%' . $type. '%" AND `price` LIKE "%' . $price . '%"
I am wondering if there is a way to say ‘all’ if nothing is entered into one of the fields. For example if they do not enter a value in the price field is there a way to tell SQL to just say ignore that section, eg:
AND `price` LIKE "*";
So the reuslts are still filtered by Brand and Type but can have any Price.
Any advice on this is appreciated! Thanks
As Ariel mentioned, it would be better to have PHP do the filtering as you build the query. Here’s a code sample for doing it that way:
NOTE: Please, please, please make sure that the
$brand,$type, and$pricevariable contents are sanitized before you use them this way or you make yourself vulnerable to SQL injection attacks (ideally you should be using the PHP PDO database connector with prepared statements to sanitize the input).