【问题标题】:Where_in statement in a query built with codeigniter with an string that should be an array使用 codeigniter 构建的查询中的 Where_in 语句,其字符串应为数组
【发布时间】:2018-11-20 23:45:45
【问题描述】:

查询的where_in 子句中的 CodeIgniter 存在问题。

让我们看一下描述问题的查询:

WHERE `table`.`table_row` IN ('7296 ,7314 {and so on});

这是我在CodeIgniter(表达式引擎)中查询的结果是

$sql = ee()->db->where_in('table.table_row', $entry_ids);

我的数组$entry_ids 是一个字符串,是我之前在代码中获得的:

$entry_ids = $ee->TMPL->fetch_param('e_id');

我的查询应该是:

WHERE `table`.`table_row` IN ('7296' ,'7314' {and so on});

我已经尝试指定我的数组实际上是一个数组,而不是一个字符串:

$entry_ids[] = $ee->TMPL->fetch_param('e_id');

但实际上,什么都没有改变。

【问题讨论】:

  • 你遇到了什么错误?请分享您的整个代码
  • 没有逗号分隔每个值,或者列表(数字)的开头和结尾有逗号
  • 什么类型的字符串只是显示一个例子,这样很容易纠正问题
  • WHERE table.table_row IN ('7296 ,7314') 将失败,因为它不会返回任何内容。正如我所说,它应该是 WHERE table.table_row IN ('7296' ,'7314') 或 WHERE table.table_row IN (7296 ,7314)
  • 看到这个:eval.in/1019052

标签: php codeigniter mysqli codeigniter-3 where-in


【解决方案1】:

因此,您有存储为字符串的 id 列表,您希望将其作为 IN 语句进行查询。

首先将您的字符串拆分为一个数组:
如果您的 id 由字符串分隔:

$id_array = explode(" ", $string_of_ids);

如果您的 id 用逗号分隔:

$id_array = explode(",", $string_of_ids);

如果您的 id 用逗号和单引号分隔:

$id_array = explode("','", $string_of_ids);

然后您可以将 $id_array 传递到您的查询中:
如果您的 id 列是 int 类型:

$this->db->where_in('table.table_row', $id_array);

如果您的 id 列是字符串类型: 只需将单引号添加到您的 ID:

$id_array = "'" . join("','", $id_array) . "'";
$this->db->where_in('table.table_row', $id_array);

再一次,如果你的 $string_of_ids 包含你的 id 的引号,你可以跳过一个步骤:

$id_array = explode(",", $string_of_ids);

这应该保留您的报价,因此您不必再次加入。

【讨论】:

    【解决方案2】:

    希望对您有所帮助:

    使用explode 将字符串放入数组中

      $string = '7296 ,7314'; // string of ids
      $entry_ids = explode(',', $string);
      //print_r($entry_ids);
    
      $this->db->where_in('table.table_row',$entry_ids); //use in where clause
    

    工作演示:https://eval.in/1019052

    了解更多http://php.net/manual/en/function.explode.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 2013-11-14
      • 1970-01-01
      • 2016-10-13
      • 2019-03-23
      相关资源
      最近更新 更多