0

I have this query

SELECT * 
  FROM `Products` 
 WHERE brand REGEXP '$brandFilter' 
   AND categories REGEXP '$categoryFilter' 
   AND color REGEXP '$colorFilter' 
   AND price BETWEEN '$priceMin' AND '$priceMax' 
   AND size REGEXP '$sizeFilter'

I work with PHP and every value obtained can be empty It is possible to check in SQL if the value is empty? for example: if '$brandFilter' is not null

SELECT * 
  FROM Products
 WHERE brand REGEXP '$brandFilter'

It is possible to do this in code but it is very long because it is possible to get 3 values null

thanks for your help!

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43
B RAMI
  • 19
  • 1
  • 5

1 Answers1

0

From SQL perspective, you need OR conditions:

SELECT * 
FROM Products 
WHERE (brand      REGEXP :brandFilter    OR :brandFilter    IS NULL)
  AND (categories REGEXP :categoryFilter OR :categoryFilter IS NULL)
  AND (color      REGEXP :colorFilter    OR :colorFilter    IS NULL)
  ...

You might want to dynamically build the where clause in your application, which would probably make for more efficient SQL code.

Note that this uses bind parameters rather that concatenating variables in the query string. Recommended reading: How can I prevent SQL injection in PHP?.

GMB
  • 216,147
  • 25
  • 84
  • 135