user6818018
user6818018

Reputation:

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.

Upvotes: 0

Views: 1306

Answers (2)

Pradeep
Pradeep

Reputation: 9707

Hope this will help you:

Use explode to get your string into an array

  $string = '7296 ,7314'; // string of ids
  $entry_ids = explode(',', $string);
  //print_r($entry_ids);

  $this->db->where_in('table.table_row',$entry_ids); //use in where clause

Working demo:https://eval.in/1019052

For more http://php.net/manual/en/function.explode.php

Upvotes: 0

Mike J
Mike J

Reputation: 425

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.

Upvotes: 1

Related Questions