I have a page for browsing db records. The viewer can filter records by category, author, and tags. I'm using a form instead of url segments for filtering records (it feels more secure because I can validate inputs.)
For instance, when all form inputs are populated the query looks like this:
SELECT * FROM (`posts`) WHERE `category` = 'technolgy' AND `author` = 'lila' AND `tags` = 'ebook'
However if one input or more is empty, I get no results. For example:
SELECT * FROM (`posts`) WHERE `category` = '' AND `author` = 'lila' AND `tags` = ''
I want the inputs to be optional so for example if just author name
is entered, I can return records made by that author regardless of category and tags. How can I omit the and where
clause if empty?
Note: or_where
clause is not the solution because it doesn't return a precise query if all filter inputs all filled.
My Model
function filter($form_values)
{
$query = $this->db->get('posts');
$this->db->where($form_values); //adds clause to all array items
return $query->result();
}
The function parameter is an array with input values from my view. Example,
$form_values = array('category' => $category, 'author' => $author, 'tags' => $tags);
and my View
$form_values = array (
'category' => $this->input->post('category'),
'author' => $this->input->post('author'),
'tags' => $this->input->post('tags')
);
$this->Records_model->filter($form_values);
I know that in Codeigniter if $_POST'
are empty they are set to FALSE
. Can that be used to achieve what I'm trying? I'm not sure if I'm on the right track