I have a query of the form SELECT * FROM products WHERE 'id'= $id, 'name' = $name' ; finds nothing if one of the variables is undefined (null).

How to correctly construct a query with variables provided in the value of null, so that the choice works only where there is no null. So that if $ name is not known, then lines with $ id are output. If both parameters are known, then all rows.

In reality, I need a query with 5 parameters, so I want the condition here to be the query, not the if. And the default values ​​don't suit me either (unless there is an ALL value).

  • one
    I wonder how your commas in where work ... And apparently it is something like (id=$id or $id is null) and (name=$name or $name is null) - Mike
  • if it is necessary that the variable (not the column) is not taken into account in the condition, then it is better to check for null and then dynamically generate the query condition. - Sanya_Zol
  • thanks aha, concatenating a query while checking variables to zero solves the problem - Vladimir Vasilev

3 answers 3

This is of course a crutch, but it will work:

 Select ....... where (id = $id or $id is null) and .... 

    Something like this?

    SELECT * FROM products WHERE ('id'= $id) AND ('name' = CASE WHEN $name IS NULL THEN 'name' ELSE $name END)

      Thanks to everyone, it’s somehow difficult to get a pure request, I found an alternative solution to make a request by concatenation (assuming non-null variable values)

      • Means dynamic request? - Anatol