0

I have the following SQL statement:

"SELECT * 
FROM products 
WHERE productage >= '$age' 
  AND productbrand='$brand'
  AND productinterest='$interest'
  AND (productprice >= '50' OR productprice='none')
  AND productexpdate >= CURDATE();"

If however $age, $brand or $interest is "all" I would like them not to even be displayed, showing everything in the products table under that variable. Is this possible or would I need to make multiple SQL statements depending on what the $age, $brand or $interest value is?

I hope you understand my question, please let me know if not!

Stu
  • 30,392
  • 6
  • 14
  • 33
  • 2
    (Possible) side note: Do not use string interpolation or concatenation to get values into SQL queries. That's error prone and might make your program vulnerable to SQL injection attacks. Use parameterized queries. See ["How to include a PHP variable inside a MySQL statement"](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) and ["How can I prevent SQL injection in PHP?"](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – sticky bit Dec 04 '21 at 19:17
  • 2
    Just check each variable in php and don't include that portion of code if that variable is `'all'`. It's just a string builder problem then. – MatBailie Dec 04 '21 at 19:20
  • 2
    Also a price as a `varchar` is wrong. Use a numeric type and if there is no price, use `NULL` as value, not `'none'`. – sticky bit Dec 04 '21 at 19:23

1 Answers1

0

OR the 'all'

... 
WHERE ('$age' = 'all' OR productage >='$age') 
  AND ('$brand'='all' OR productbrand='$brand') 
  AND ('$interest'='all' OR productinterest='$interest')
...
LukStorms
  • 28,916
  • 5
  • 31
  • 45