CodeIgniter - query binding “IN” parameter

China☆狼群 提交于 2019-12-23 01:19:07

问题


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.


回答1:


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');



回答2:


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);



回答3:


$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




回答4:


Use FIND_IN_SET like this

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



回答5:


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.




回答6:


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);



回答7:


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


来源:https://stackoverflow.com/questions/16436809/codeigniter-query-binding-in-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!