Welcome Guest, Not a member yet? Register   Sign In
Query Binding Using IN Clause with either string array or string list - Not Using Active Record
#1

[eluser]Unknown[/eluser]
CodeIgniter cannot seem to handle Query Binding using IN. Below is an example which seems to fail. I have tried several ways of getting $arrayOfIds below into the correct syntax for the id IN (?) with no luck. If I do not query bind, it works. There has to be answer.

Example:

Code:
// this is actually being passed in as argument
$arrayOfIds = array('A0000-000000000001','B0000-000000000001','C0000-000000000001');  

$params = array();
array_push($params,1); // for the status
array_push($params, "'" . implode("','",$arrayOfIds) . "'"); // for the id in

$sql = "SELECT name FROM my_table WHERE status = ? AND id IN (?) ";

$query = $this->db->query($sql,$params);


Solution:
CodeIgniter appears to escape all bound query params. So you end up with IN ('\'A0000-000000000001,B0000-000000000001,C0000-000000000001'\'') -OR- ('\'A0000-000000000001\',\'B0000-000000000001\',\'C0000-000000000001\''). However, as suggested by Yan Berk on StackOverflow, you can create a bind variable containing the appropriate amount of bind params (results in "?,?,?) and the merge the id array to the query param array.

Code:
$arrayOfIds = array('A0000-000000000001','B0000-000000000001','C0000-000000000001');  

$params = array();
array_push($params, 1);

$params = array_merge($params, $arrayOfIds);
$in_string = str_replace(' ', ',', trim(str_repeat("? ", count($arrayOfIds))));  

$sql = "SELECT name FROM my_table WHERE status = ? AND id IN (".$in_string.")";

$query = $this->db->query($sql, $params);
URL: http://stackoverflow.com/questions/19758...tring-list





Theme © iAndrew 2016 - Forum software by © MyBB