Search code examples
phpcodeignitermysqlicodeigniter-3where-in

Where_in statement in a query built with codeigniter with an string that should be an array


Problem with CodeIgniter in a where_in clause for a query.

Let's have a look on the query to describe the problem:

WHERE `table`.`table_row` IN ('7296 ,7314 {and so on});

This is the result of my query in CodeIgniter (expression engine) is

$sql = ee()->db->where_in('table.table_row', $entry_ids);

My array $entry_ids is a string, that I obtained previously in my code:

$entry_ids = $ee->TMPL->fetch_param('e_id');

To work my query should be:

WHERE `table`.`table_row` IN ('7296' ,'7314' {and so on});

I've already try to specify that my array is actually an array, not a string:

$entry_ids[] = $ee->TMPL->fetch_param('e_id');

But actually, nothing changed.


Solution

  • So you have list of ids stored as a string, which you want to query off of as an IN statement.

    First split your string into an array:
    If your ids are separated by a string:

    $id_array = explode(" ", $string_of_ids);
    

    If your ids are separated by commas:

    $id_array = explode(",", $string_of_ids);
    

    If your ids are separated by commas and single quotes:

    $id_array = explode("','", $string_of_ids);
    

    Then you can pass $id_array into your query:
    If your id column is of type int:

    $this->db->where_in('table.table_row', $id_array);
    

    If your id column is of type string: Just add single quotes to your ids:

    $id_array = "'" . join("','", $id_array) . "'";
    $this->db->where_in('table.table_row', $id_array);
    

    Then again, if your $string_of_ids contain quotes around your ids, you could probably skip a step by just doing:

    $id_array = explode(",", $string_of_ids);
    

    That should leave your quotes in place, so you don't have to join again.