[英]Array to comma separated strings
This is the code (I'm using Codeigniter): 这是代码(我正在使用Codeigniter):
$sql = 'SELECT * FROM foo WHERE bar IN (?)';
$query = $this->db->query($sql, array($values));
So $values is an array of strings that I want to add in the SQL statement where the "?" 所以$ values是一个字符串数组,我想在SQL语句中添加“?” is.
是。 When I try this I get an "Array to string conversion" error.
当我尝试这个时,我得到一个“数组到字符串转换”错误。 Is there any way I can add the values of the $values array as comma separated strings into the SQL statement?
有没有什么办法可以将$ values数组的值作为逗号分隔的字符串添加到SQL语句中?
You should pass string with comma separated in query. 您应该在查询中使用逗号分隔传递字符串。 for that use
implode
function of php. 为此使用内
implode
功能的PHP。
Do like this: 这样做:
$values = array('bar1', 'bar2', 'bar3');
$string = "'".implode("',", $values)."'";
Then pass string in the query, 然后在查询中传递字符串,
$sql = 'SELECT * FROM foo WHERE bar IN ($string)';
$query = $this->db->query($sql);
echo '<pre>'; print_r($query->result_array());
You will data in $query variable. 您将在$ query变量中输入数据。
Let me know for further help if needed. 如果需要,请告诉我进一步的帮助。
Why don't you use simple codeigniter way 为什么不使用简单的codeigniter方式
$this->db->from('foo');
$this->db->where_in('bar',$values);
$query=$this->db->get();
This will produce what you exactly want 这将产生你想要的东西
Update 更新
If you are strict with your way you need to produce the $sql this way 如果你对你的方式很严格,你需要以这种方式生成$ sql
$sql = 'SELECT * FROM foo';
if(is_array($values)&&sizeof($values)>0)
{
$sql.=' WHERE bar IN (';
foreach($values as $key=>$value)
{
if($key==0)
{
$sql.='?';
}
else
{
$sql.=',?';
}
}
$sql.=')';
}
$query=$this->db->query($sql,$values);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.