php - Codeigniter omit where clause for empty criterion -
i have page browsing db records. viewer can filter records category, author, , tags. i'm using form instead of url segments filtering records (it feels more secure because can validate inputs.)
for instance, when form inputs populated query looks this:
select * (`posts`) `category` = 'technolgy' , `author` = 'lila' , `tags` = 'ebook' however if 1 input or more empty, no results. example:
select * (`posts`) `category` = '' , `author` = 'lila' , `tags` = '' i want inputs optional example if author name entered, can return records made author regardless of category , tags. how can omit and where clause if empty?
note: or_where clause not solution because doesn't return precise query if filter inputs filled.
my model
function filter($form_values) { $query = $this->db->get('posts'); $this->db->where($form_values); //adds clause array items return $query->result(); } the function parameter array input values view. example,
$form_values = array('category' => $category, 'author' => $author, 'tags' => $tags); and 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 in codeigniter if $_post' empty set false. can used achieve i'm trying? i'm not sure if i'm on right track
you correct $this->input->post() return false if $_post value not set. unless want is null part of query (which believe happen passing false param 2 of where(), not 100% sure), filter out empty values:
function filter($form_values) { $form_values = array_filter($form_values); // note: // where() needs called first, or query won't use clause // may need make sure there @ least 1 value in $form_values if ( ! empty($form_values)) // wish check value { $this->db->where($form_values); //adds clause array items } $query = $this->db->get('posts'); return $query->result(); } http://php.net/manual/en/function.array-filter.php
the important part note on array_filter():
if no callback supplied, entries of input equal false (see converting boolean) removed.
Comments
Post a Comment