Reputation: 161
I am trying to build a query and this is its WHERE
clause so far:
WHERE ( s.subject_name LIKE '%$keyword%' OR
c.city_name LIKE '%$keyword%' OR
o.option_name LIKE '%$option%' OR
d.district_id = $districtId OR
c.city_id = $cityId
)
My actual conditions are:
$keyword
should always hold a value. Other 3 may not.$keyword
has a value, returned records should match
$keyword
in subject_name
or city_name
. $optional
have a value, then returned records should match $keyword
and
$option
$districtId
has a value, then results should match the 3 variable values ($keyword
, $option
, $districtId
) $cityId
has a value along with the other 3, returned result should match all 4 variables' values. These conditions come from my search page. $keyword
is the value from a text box and a keyword is required to start searching. That's why I said it always has a value. Other 3 values come from select boxes that allows to select the items when they are needed.
I tried to make the query, its ok. But I am really confused with the WHERE
clause. Above code is from my WHERE
clause so far. But I can not get my desired result.
Upvotes: 0
Views: 133
Reputation: 29769
If you want to achieve this in pure SQL, this is what you need (or at least it should be close enough):
WHERE (
( s.subject_name LIKE '%$keyword%' OR c.city_name LIKE '%$keyword%' )
AND ('$option' = '' OR (
o.option_name LIKE '%$option%' AND (
'$districtId' = '' OR (
d.district_id = $districtId AND (
'$cityId' = '' OR c.city_id = $cityId
)
)
)
)
)
However, this is by far sub-optimal. Instead, you should check the contents of user input in PHP and run a different query depending on this input. You could also build the query dynamically:
$query = "SELECT ...";
$query .=
" WHERE ( ( s.subject_name LIKE '%$keyword%' OR c.city_name LIKE %$keyword%' )";
if ( !empty($option) ) {
$query .= " AND o.option_name LIKE '%$option%'";
if ( !empty($districtId) ) {
$query .= " AND d.district_id = $districtId";
if ( !empty($cityId) ) {
$query .= " AND c.city_id = $cityId";
}
}
}
$query .= ')';
Upvotes: 1