Reputation: 147
I have 2 variables in PHP (let's call them 'var1' and 'var2') and a sql command like this:
$sql = "SELECT `id`, `name` FROM `table` WHERE `var` = '{$var1}'"
if ($var2) {
$sql.= "AND `var`={$var2}"; }
Variable var1
it is always set, but var2 not. I want when var 2 is set to apply WHERE clause only for var2. This means that var2 is more restrictive than var1. How can i do this in SQL language.
Upvotes: 0
Views: 73
Reputation: 34406
If I understand you correctly you want to do this -
$sql = "SELECT `id`, `name` FROM `table` ";
if($var2) {
$sql .= "WHERE `var` = '{$var2}'";
} else {
$sql .= "WHERE `var` = '{$var1}'";
}
If you want to do this just using SQL you would use something like this -
SELECT `id`, `name`, `variable`
CASE variable
WHEN 'var1' = variable THEN a = var1
WHEN 'var2' = variable THEN a = var2
END
FROM `table`
WHERE `foo` = a
Without knowing more of your code or having sample data to work with it is hard to develop a demo, but this should get you started.
Upvotes: 2
Reputation:
if ($var2) {
$sql = "SELECT `id`, `name` FROM `table` WHERE `var` = '{$var2}'";
} else {
$sql = "SELECT `id`, `name` FROM `table` WHERE `var` = '{$var1}'";
}
Upvotes: 1