Search code examples
phpcodeignitercodeigniter-3where-indelimited

How to use a comma-separated string in CodeIgniter's where_in() method


I have some id stored in database table with column name "defaultdest" like "1,2,3,4,5,6". I have fetched it in controller and now I need to make query in my another table that is named "destinations". where I need to fetch the destinations according to Ids is "1,2,3,4,5,6".

here is the query result from another table

public function index()
{
    $data = $this->data;
    $idlists = explode(",", get_option('defaultdest'));
    $data['destlist'] = $this->ui_model->destfetch($idlists);
    $this->load->view('themes/ui/home/'.get_option('uihometype').'', $data);
}

This is my database query in model

function destfetch($idlists)
{
    $this->db->set_dbprefix('');
    $this->db->select('*');
    $this->db->where_in('id', $idlists);
    $this->db->from("destinations");
    $query = $this->db->get();

    //print_r($this->db->last_query());
    return $result = $query->result_array();   
} 

Note: idlists values are (returned by get_option method)

$idlists = "1,2,3,4,5,6";

This is not working, getting blank results.


Solution

  • Where_in works with array not a string. So your $idlists shouldn't be a string with '1,2,3,4,5' but an array of ids.

    You can do this by just doing:

    $idlists = "1,2,3,4,5,6";            //String
    $this->db->where_in('id', explode(',', $idlists));
    

    Note:- explode() use for breaks a string into an array.