Timothy Fisher Timothy Fisher - 1 month ago 8
PHP Question

How to get rid of unused $_GET parameters in URL with Codeigniter?

I am designing search functionality with some data with Codeigniter.

My search model looks like:

class Search_Model extends CI_Model {

public function get_results($search_terms = false) {

// Build query
foreach ($search_terms as $field => $value) {
$this->db->like("{$field}", $value);
}

// Execute query
$query = $this->db->get('exams');

// Return results
return $query->result_array();
}
}


And the search controller method looks like this:

public function results() {

$search_terms = array(
'first_name' => $this->input->get('first_name', TRUE),
'last_name' => $this->input->get('last_name', TRUE),
'exam_name' => $this->input->get("exam_name", TRUE)
);

$data['title'] = "Search Results";
$data['exams'] = $this->search_model->get_results($search_terms);

$this->load->view('templates/header.php', $data);
$this->load->view('exams/index.php', $data);
$this->load->view('templates/footer.php');
}


The search is working as it should but I want to clean up the URL which comes out something like this if I only search for "First Name":

search/results?first_name=tim&last_name=&exam_name=


How can I remove those extra parameters that are unused in the URL?

Answer

The quickest way is just to filter the $searh_terms array before passing it to the model.

$search_terms = array(
    'first_name' => $this->input->get('first_name', TRUE),
    'last_name' => $this->input->get('last_name', TRUE),
    'exam_name' => $this->input->get("exam_name", TRUE)
);

// Remove empty search values
foreach ($search_terms as $key => $value) {
    if (strlen($value) == 0) {
         unset($search_terms[$key]);
    }
}
Comments