【问题标题】:Getting incorrect query in codeigniter在 codeigniter 中获取不正确的查询
【发布时间】:2012-12-21 11:54:34
【问题描述】:

当我使用上面的$id值从mysql表中获取记录时,我通过控制器将变量值作为$id="'10','11',12'"从视图传递到模型:

$query=$this->db->query('select * from userdetails where Id IN ($ids)')

我没有得到结果,但它将查询打印为:

SELECT * FROM (`userdetails`) WHERE `Id` IN ('\'10\',\'11\',\'12\'')

如何解决这个问题?

【问题讨论】:

  • 还可以尝试打印查询和查询的值。或者向我们展示您的代码的更多详细信息。
  • 为什么你会得到 ids 的引号......是那些 ids 字符串......尝试使用 Bhuvan Rikka 所说的内爆......我也在我的应用......
  • 您不能将值作为$id="10,11,12" 传递吗?将它们作为字符串传递的任何具体原因?
  • @lalith 如果解决了问题,请提供更多已接受的答案。

标签: php mysql codeigniter


【解决方案1】:

好的,试试这个:

$this->db->escape($id);
$query=$this->db->query("select * from userdetails where Id IN ($ids)");

在传入查询之前使用stripslashes($id);。或者mysql_real_escape_string() 也应该可以工作。
这样:

$ids = stripslashes($ids);
$query=$this->db->query("select * from userdetails where Id IN ($ids)");

或者您可以通过这种方式发送以逗号分隔的值 $ids = "11,12,13"; 它应该可以工作。

【讨论】:

  • 顺便说一句 $this->db->查询可能无法正常工作,因为您使用的是单引号。
  • 这是有效的,但是当我们将查询编写为 $this->db->select('*')->from('userdetails')->where_in('Id',$ids ); $query=$this->db->get();它不起作用,获取查询为 SELECT * FROM (userdetails) WHERE Id IN ('\'10\',\'11\',\'12\'')
【解决方案2】:

在数组中发送 id...

$id_array = array('10','11','12');

型号:

//implode converts your array into a string without quotes
$comma_separated = implode(",",$id_array);
$query=$this->db->query('select * from userdetails where Id IN ($comma_separated)');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 2016-03-20
    • 1970-01-01
    • 2017-10-09
    • 2017-01-04
    • 1970-01-01
    • 2017-11-19
    • 2019-08-29
    相关资源
    最近更新 更多