1

I have a following query in my CodeIgniter, which I'm trying to bind via parameter.

$q = "SELECT * FROM my_table WHERE id IN (?)"
$ids = "1,2,3,4";
$this->db->query($q, array($ids));

Above is not working, because the query binding treats $ids as string. How can I parameterize my query, but still be able to do "IN" operation?

EDIT

sorry, I have to use "raw SQL query". Above query is just a part of a much larger + complex query, which I can't use ActiveRecord for. Also I'm using Postgres.

4
  • Maybe FIND_IN_SET() ? Just a workaround, if no suitable answers supplied. Commented May 8, 2013 at 9:15
  • @ericbae I have updated my answer check that. Commented May 8, 2013 at 9:32
  • @ericbae are u enclosing $ids with single quotes??? in the query? Commented May 8, 2013 at 9:33
  • $this->db->query($q, explode(",",$ids)); Commented May 8, 2013 at 9:48

7 Answers 7

2

Instead of string put it in array

$q = "SELECT * FROM my_table WHERE id IN (?)"
$ids =  array(1,2,3,4);
$this->db->query($q, $ids);

You can achieve same thing like this without binding

Alternative

$ids =  array(1,2,3,4);
$this->db->where_in('id',$ids);
$this->db->get('my_table');
Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting an error on this - it's interpreting it as string "Array" - error on "id IN (Array)"
0

Try this with where_in

$ids = array(1,2,3,4);
$this->db->select('*');
$this->db->from('my_Table');
$this->db->where_in('id',$ids);

Comments

0
$this->db->query($q, explode(',', $ids));

or

$this->db->where_in('id', explode(',', $ids))->get('my_table');

Active Records documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html#select

Comments

0

Use FIND_IN_SET like this

select * from table where FIND_IN_SET('$ids', id);

1 Comment

0

Try this code:

$ids = "('1','2','3','4')";
$q = "SELECT * FROM my_table WHERE id IN ".$ids;
$this->db->query($q);

you should use the

$ids = array('1','2','3','4');
$this->db->where_in('id', $ids);

The where_in is used in codignitor.

3 Comments

I don't think that will sanitize the parameter $ids and prevent it from SQL injection.
@ericbae If you are affair ed with sql injection then why are using the query to execute and there is used PDO in codignitor so be cool.
Of course, it wouldn't be safe, stable to pass untrusted data into the query this this.
0

point is

$ids = "1,2,3,4";
$a = array($ids);
//$a[0] = "1,2,3,4";

//not  $a[0]=1;$a[1]=2;$a[2]=3;$a[3]=4;

want to keep your style

 $ids = "1,2,3,4";
$a = explode(",",$ids);

Comments

0
$q = "SELECT * FROM my_table WHERE id IN ?"
$ids = "1,2,3,4";
$this->db->query($q, explode(",", $ids));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.