Search code examples
phpmysqlcodeignitercodeigniter-3codeigniter-query-builder

I want to build an advanced query in codeigniter


I want to build a query nested in codeigniter

here is the my controller

    public function advancedSearch(){
        if (!$this->session->userdata('logged_in')) {
            redirect('main/login', 'refresh');
        }
        $session_data = $this->session->userdata('logged_in');
        $data['code'] = $session_data['code'];

        $start = $this->input->post('start');
        $end =$this->input->post('end');
        $ticket = $this->input->post('ticket');
        $type =$this->input->post('type');
        $this->db->select('*');
        $this->db->from('table');

        if ($start && $end) {
            $this->db->where('date >=',$start);
            $this->db->where('date <=',$end);
        } else if ($ticket) {
                $this->db->where('ticket','yes');
        } else if ($type) {
            $this->db->where('type',$type);
        }
        $query = $this->db->get();

    if ($query->num_rows() > 0) {
      $data['data'] = $query->result();
    }
//print_r($data);
        $this->load->view('advanced-search',$data);

with this code I just get the first input a click and search, If I click just ticket I get the $this->db->where('ticket','yes'); I hope I explained well.

Greetings


Solution

  • Hope this will help you :

    instead of using if else use it with only if with empty check

    if ( ! empty($start)) 
    {
      $this->db->where('date >=',$start);
    } 
    if (! empty($end))
    {
      $this->db->where('date <=',$end);
    }
    if (! empty($ticket)) 
    {
      $this->db->where('ticket','yes');
    }
    if (! empty($type)) 
    {
       $this->db->where('type',$type);
    }
    
    $query = $this->db->get();
    
    if ($query->num_rows() > 0) 
    {
      $data['data'] = $query->result();
    }
    //print_r($data);
    $this->load->view('advanced-search',$data);