首页 > 解决方案 > 将逗号分隔的字符串传递给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时,它没有显示那个记录。

标签: phpmysqlcodeigniter

解决方案


删除以下行:

$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


推荐阅读