MySQL: Select WHERE x=anything

Soldato
Joined
27 Dec 2005
Posts
17,316
Location
Bristol
I'm building a directory that for now will have two user-filterable selections: region and category.

Question is, do I need a separate MySQL query for every combination? Because for the life of me I can't find a wildcard should either filter not be chosen.

PHP:
$region = preg_replace('/\W/si', '', $_GET['reg']);
$category = preg_replace('/\W/si', '', $_GET['cat']);
if(!$region){$region = "%";}
if(!$category){$category = "%";}

$sql = mysql_query("SELECT * FROM table WHERE region='$region' AND servicetype='$category' ORDER BY businessname"); 
$sqlcheck= mysql_num_rows($sql);

% is the wildcard for MySQL but neither this nor * work. Is there a simple way of doing this a la above or do I need to create a separate MySQL query based on if($region) etc? Although that's not so much work right now it could get extremely tedious once there's more filterable options.
 
Last edited:
If you want to use '%' then you need to use LIKE not =.

If you don't care what the region is then remove it altogether from the where clause.
 
Last edited:
Back
Top Bottom