php - 将逗号分隔的字符串传递给codeigniter中的in子句
问题描述
我想将逗号分隔的字符串传递给IN
子句。我的控制器代码如下:-
$batchpost = $this->input->post('batch');//print_r($batch);
$batch_id = '';
for($i=0;$i<count($batchpost);$i++ ) {
$batch_id = $batch_id . $batchpost[$i] . ',';
}
$batch_string = rtrim($batch_id, ',');
$batch = str_replace(",", ",", $batch_string) ;
$list = $this->admin_model->get_attendance_datatables($batch);
这里$batchpost
将返回数组值,我想将其转换为逗号分隔的字符串并传递给模型。
我的模型代码如下:-
$this->db->select('offline_student.*,batch.batch_name,offline_course.course');
$this->db->from($this->table8);
$this->db->join('offline_course', 'offline_course.id = offline_student.course', 'left');
$this->db->join('batch', 'batch.id = offline_student.batch', 'left');
$this->db->where('offline_student.status', 'Active');
$this->db->where_in('batch.id', $batch);
$this->db->order_by('offline_student.id', 'asc');
假设在数据库中有两个值(2,3)的批处理列的一行中,如果我只将'2'或'2,3'传递给模型,查询将返回我的结果,但是当我只传递3时,它没有显示那个记录。
解决方案
删除以下行:
$batch_id = '';
for($i=0;$i<count($batchpost);$i++ ) {
$batch_id = $batch_id . $batchpost[$i] . ',';
}
$batch_string = rtrim($batch_id, ',');
$batch = str_replace(",", ",", $batch_string) ;
...并使它像这样:
$batchpost = $this->input->post('batch');//print_r($batch);
$list = $this->admin_model->get_attendance_datatables($batchpost);
您不需要转换$batchpost
为逗号分隔的字符串,因为where_in()
方法的第二个参数需要一个数组。
where_in()
请参阅此处的文档https://www.codeigniter.com/userguide3/database/query_builder.html#looking-for-specific-data
推荐阅读
- asp.net - 为什么 asp.net web api 响应得到太多时间
- c# - 如何将参数子字符串转换为 C# 中的列类型?
- javascript - 将跨度值除以静态数字 - JS
- automapper - AfterMap 与 IMappingAction 和 IHttpContextAccessor 抛出错误
- php - Yii2 - 使用 Ajax 加载为 Select2 插件设置值
- php - PDO 获取第二列作为第二个数组的键
- r - Adding an "ALL" option to dynamic selectInputs
- python - 与 dictwriter 一起使用时如何在 python 中正确删除回车(newline='' 没有帮助)
- python - Matplotlib/basemap: plot a line with different colors, based on depending values
- jestjs - Babel7 Jest unexpected token export