IF-ELSE in WHERE clause of query

Hi everyone,

I need something like an IF-ELSE statement in the WHERE clause of my query.

$q = "SELECT …FROM …WHERE name = ‘$name’ if (isset($country)) echo && ‘$country’ ";

If the $country variable is set then the query needs to run with the value of that variable, otherwise the query runs without that value.

Thanks in advance!!

And Season’s greetings/happy holidays to you all!!

You could append a condition to the query something like this:

$q="SELECT * FROM `mytable` WHERE `name`='$name'";

if(isset($country))){
$q.=" AND `country`='$country'";
}

Thanks Force Flow,

I’ll give that a try!

Okay, I’ve tried the code and it works - thanks. One problem though is that one of my queries contains a LIMIT at the end of the query:

$q = "SELECT …FROM …WHERE name = ‘$name’ LIMIT $somevariable ";

All of the conditions need to be positioned before the LIMIT otherwise the query fails. Do you know what I can do in this situation?

Thank you.

Couldn’t you simply append it to the $q string before you use it?

Hi all,

it’s working, thank you.