You may be interested in using the CI Active Record class:
In addition to simplicity, the main advantage of using Active Record features is that it allows you to create database-independent applications, because the query syntax is generated by each database adapter. It also allows safe queries, since the values are automatically escaped by the system .
Your rewritten request will look like this (assuming $id is an array):
$this->db->where_in('toy_id', $id)->get('toys');
Also: I admit I'm a bit confused, as it looks like $ids would be a more suitable variable name and the way you use it in a query, I would assume this is a string ...
If the active record is not your thing, you can also find Query Bindings :
The second advantage of using bindings is that the values are automatically escaped , creating more secure queries. You do not need to forget to manually delete data; the engine does this automatically for you.
EDIT . Looking back, it looks like what you are trying to do. In this case, try replacing:
$sql = "select * from toys t where t.toy_id in ($id)";
FROM
$sql = "select * from toys t where t.toy_id in (?)";
And pass $id as the second argument to query() , but as a comma-separated string ( implode(',', $id) if $id is really an array).
Otherwise, you can use $this->db->escape_str() .
$ this-> db-> escape_str () This function skips the data passed to it, regardless of type.
Here is an excerpt from the mysql driver source code to perhaps calm your mind.
function escape_str($str, $like = FALSE) { if (is_array($str)) { foreach ($str as $key => $val) { $str[$key] = $this->escape_str($val, $like); } return $str; }
It iterates over arrays and avoids their values.
It seems that $this->db->escape will not work for arrays.
$ this-> db-> escape () This function defines the data type so that it can only escape string data.
Here is the source:
function escape($str) { if (is_string($str)) { $str = "'".$this->escape_str($str)."'"; } elseif (is_bool($str)) { $str = ($str === FALSE) ? 0 : 1; } elseif (is_null($str)) { $str = 'NULL'; } return $str; }
It looks like it is ignoring arrays.
In any case, I hope you find a solution that works for you. My vote for Active Record.