I my table I have one column 'x' that is either 1 or 0. I need a MySQL query that returns either all rows, or those where x = 1 or where x = 0.
Which one of those threee results I want is set in a variable $type. What I did is create three queries and a if clause:
if ($type == 'all') $query = "SELECT * FROM contracts";
elseif ($type == 'n') $query = "SELECT * FROM contracts WHERE x = '0'";
elseif ($type == 'f') $query = "SELECT * FROM contracts WHERE x = '1'";
This works but I does not seem the best solution to me because I have to write 3 times an almost same query and if I want to change something I have to change it 3 times.
I tried to make $type = '', 0 or 1 and then WHERE x = '$type'
but that did not work.
How would I do this using only one MySQL Query?
if ($type = 'all') {
$filter = '';
} elseif ($type == 'n') {
$filter = "WHERE x = '0'";
} elseif ($type == 'f') {
$filter = "WHERE x = '1'";
} else {
die("Invalid filter type: $type");
}
$query = "SELECT * FROM contracts $filter";
If you use the scheme where $type = '', 0, or 1
, you can do:
$query = "SELECT * FROM contracts";
if ($type !== '') {
$query .= " WHERE x = '$type'";
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments