How to replace an empty variable with the curing character in the WHERE clause in sql

advertisements

Im passing two variables, via ajax - post method, into WHERE statement in query. Second variable $var2 is optional and it may or may not be sent. That means that second variable can be empty and query would not return any result.

SELECT table1.*
        FROM table1
        LEFT OUTER JOIN table2 ON table1.table2_id = table2.id
        WHERE table2.field1 = '".$var1."' AND table2.field2 = '".$var2."'
        ORDER BY table2.counter DESC
        LIMIT 10;

My first thought was to write if statement, something like

if(empty($var2)){
   query = ....WHERE table2.field1 = '".$var1."'...
}else{
   WHERE table2.field1 = '".$var1."' AND table2.field2 = '".$var2."'
}

Second thought was to assign * wildcard to $var2 if it is empty(this is not working).

Is there better way than if statement that could handle this problem?

Thanks


This approach is correct;

if(empty($var2)){
   query = ....WHERE table2.field1 = '".$var1."'...
}else{
   WHERE table2.field1 = '".$var1."' AND table2.field2 = '".$var2."'
}

Add or take away from the query depending on the arguments. I do not think there is a wildcard like you want. Even if there was it doesn't matter, as omitting the second statement using an if has the same effect.