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

标签 php mysql codeigniter

我想将逗号分隔的字符串传递给 IN 子句。我的 Controller 代码如下:-

        $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

关于php - 将逗号分隔的字符串传递给 codeigniter 中的 in 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51152600/

相关文章:

mysql - 仅从两个实体中获取匹配的记录

mysql - 如何更新mysql中的2个表?

php - 如何在codeigniter中使用if条件、And条件和where条件编写选择查询

mysql - 点燃数据表中的限制

PHP/CodeIgniter关系型数据库数组搭建

php - 我有一个充满 <a> 标签的 mySQL 数据库,但在 echo'ing 时链接不起作用

Mysql查询获取一个表的行作为另一个表的列,列名来自第三个表

php - 更新表单返回空白页

terminal - 从命令行调用 PHP 脚本中的函数

php - Mysql查询按月和年获取结果