It seems such a simple task, but it's hard for me to find a solution that I like. I can not find anything that could be considered something other than awkward. Here is what I work with:
There is a search form that sends variables to script processing. These variables are filters for the requested data. Depending on the user rights, depending on the filters to which they have access, there may be more or less variables. Each filter refers to a field in the table, the results of which come mainly. One option for each filter is ANY, so there is no WHERE clause.
What a good way to build a query string. Let's say four variables are returned there: $ firstname, $ lastname, $ age, $ dob. But only some users have access to the filter by $ age and $ dob.
$query = "SELECT * FROM people";
if(($firstname != 'ANY' && !empty($firstname)) ||
($lastname != 'ANY' && !empty($lastname)) ||
($age != 'ANY' && !empty($age)) ||
($dob != 'ANY' && !empty($dob))) {
$query .= " WHERE";
}
if($firstname != 'ANY' && !empty($firstname)) {
$query .= " firstname='$firstname'";
}
if($lastname != 'ANY' && !empty($lastname)) {
if($firstname != 'ANY' || !empty($firstname)) {
$query .= " AND";
}
$query .= " lastname='$lastname'";
}
...
Etc. But it looks stupid, awful and ridiculously ineffective for me. I use a slightly modified MVC pattern, so it makes sense to build methods in the search model for every possible filter?
source
share