0

I have two tables:

  • sales
  • sales_sizes

I want to do a query for sales_sizes constrained by the variables $gender, $category and $brand.

How do I do a where statement if the individual variables are set, and don't include them in the query if they are not set?

[pseudo code in brackets]

SELECT size, country
FROM `sales_sizes` WHERE sale_id IN (
    SELECT sale_id
    FROM `sales`
    WHERE [gender = $gender if $gender isset]
    AND [category = $category if $category isset]
    AND [brand = $brand if $brand isset]

) 
2
  • are you using PDO or create a query as text? Commented Oct 3, 2013 at 8:10
  • build the querry in php? Commented Oct 3, 2013 at 8:10

2 Answers 2

1

You can gather your variables into array and then handle it like this:

$gender   = 'f';
$category = null;
$brand    = 'foo';

$rgCondition = ['gender'=>$gender, 'category'=>$category, 'brand'=>$brand];
$rgCondition = array_filter($rgCondition, function($x)
{
   //strip null-ed values:
   return isset($x);
});
$rgWhere     = [];

foreach($rgCondition as $sField=>$mValue)
{
   $rgWhere[] = '`'.$sField.'` = "'.$mValue.'"';   
}
$sWhere = count($rgWhere)?' WHERE '.join(' && ', $rgWhere):'';
//var_dump($sWhere);

-I've skipped strings escaping, but do not forget it.

Sign up to request clarification or add additional context in comments.

Comments

0

Use a CASE statement UPDATE: The previous syntax (as pointed out by a few people) doesn't work. You can use CASE as follows:

SELECT size, country
FROM `sales_sizes` WHERE sale_id IN (
    SELECT sale_id
    FROM `sales`
    WHERE [gender = $gender if $gender isset]
    AND [category = $category if $category isset]
    AND [brand = $brand if $brand isset]

)

WHERE gender
  CASE WHEN gender ($gender) = isset THEN 
    $gender 
  ELSE
    $gender='NULL'
  END

1 Comment

this won't work, look at case statement syntax dev.mysql.com/doc/refman/5.0/en/case.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.