Welcome Guest, Not a member yet? Register   Sign In
Filtering rows in Model
#1

[eluser]Unknown[/eluser]
Hello everybody.
I'm new in CodeIgniter (and probably in whole PHP) and I'm trying to write my code as well as possible.
Could you check my approach in the next task.

I have a mysql table with companies. So the task is simple: to show companies and to be able to filter them using some conditions.

So I created a controller called "Companies.php" and here I have next method:
Code:
public function getCompanies() {
  if (!$this->input->is_ajax_request()) die;
  
  $possible_filters = array('cname', 'cphone', 'caddress', 'cinn', 'ckpp', 'cfax', 'cmail', 'cregdate', 'ctype');
  for ($i = 0; count($possible_filters); $i++)
   $data['filter'][$possible_filters[$i]] = $this->input->get($possible_filters[$i]);
  
  $data['sort']['sorttype']   = $this->input->get('sorttype');
  $data['sort']['sortby']   = $this->input->get('sortyby');
  
  echo json_encode($this->companies_model->getCompanies($this->input->get('page'), $data));
}

The thing is that I must be able to filter companies, so I made an array with possible filters' names, like company name. If in my view I send a get request with cname included, I pass it to my model and it must return filtered results.

And here is my model:

Code:
function getCompanies($page, $conditions) {
  if (!$page) $page = 1;
  
  $this->db->select('*')
     ->from('COMPANIES');
  
  foreach ($conditions['filter'] as $k => $v) {
   if ($v) $this->db->like(strtoupper($k), $v); // cols have upper letters
  }
    
  $this->db->limit($this->records_per_page, $this->records_per_page*($page-1));
  
  $query = $this->db->get();
  return $query->result_array();
}

Is this code correct?
Another question is, when I user AJAX, where should I display json-encoded data? I do it in my controller, but not sure if it's a right place

Thanks in advance, code igniter is a beautiful thing! I finally felt some organization in my project!

(and sorry for my english)




Theme © iAndrew 2016 - Forum software by © MyBB