简体   繁体   中英

How to apply filter in codeigniter in 'where' condition using 'if' condition?

I am trying to apply a filter using codeigniter, but it's not working. It works for a single array record, but when I send multiple comma-separated source parameters it doesn't filter.

Here is my code in model.

    $user_id = $this->input->post('user_id');
    $source = $this->input->post('source');
    $source = explode(',', $source);

    $radius = $this->input->post('radius');

    $this->db->select('post.*, source.*, user.firstname, user.lastname');
    $this->db->from('post');
    $this->db->join('user', 'user.id = post.cop_id');
    $this->db->join('source', 'post.source_id = source.id');
    $this->db->where('post.cop_id', $user_id);
    if (in_array("1", $source)) {
        $this->db->where('post.source_id', 1);
    }
    if (in_array("2", $source)) {
        $this->db->where('post.source_id', 2);
    }

    if (in_array("3", $source)) {
        $this->db->where('post.source_id', 3);
    }

    if (in_array("4", $source)) {
        $this->db->where('post.source_id',4);
    }
    if (!empty($radius)) {
        $this->db->where('post.post_radius', $radius);
    }
    $this->db->where('post.source_id !=', 4);
    $query = $this->db->get();
    return $query->result();

Use where_in

 $this->db->select('post.*, source.*, user.firstname, user.lastname');
    $this->db->from('post');
    $this->db->join('user', 'user.id = post.cop_id');
    $this->db->join('source', 'post.source_id = source.id');
    $this->db->where('post.cop_id', $user_id);
    $this->db->where_in('post.source_id', $source);// it will produse  IN ('1', '2', '3')
    $this->db->where('post.post_radius', $radius);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM