将逗号分隔的字符串传递给codeigniter中的in子句

时间:2018-07-03 10:44:46

标签: php mysql codeigniter

我想将逗号分隔的字符串传递给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时,它没有显示该记录。

1 个答案:

答案 0 :(得分:0)

删除以下几行:

$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()方法期望在第二个参数上使用数组。

https://www.codeigniter.com/userguide3/database/query_builder.html#looking-for-specific-data处查看where_in()的文档