You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter4多选批量插入数据部分字段为空问题求助

问题:CodeIgniter4批量插入时部分字段为空

在CodeIgniter4中开发课程多选科目功能:用户勾选科目,填写对应讲师及费用,点击保存后用insertBatch批量插入数据。功能可运行,但部分数据行的讲师ID、讲师名字段为空,var_dump数组及数据库存入结果均显示对应值为空。


视图代码(mycourse.php)

<?php 
if(isset($listSubjects)){ // 检查科目数据是否获取到
    foreach($listSubjects as $listSubjects){ // 循环生成表单元素
?>
    <tr class="border border-secondary">
        <td scope="col">
            <div class="form-check">
                <input class="form-check-input" type="checkbox" name="**subject[]**" value="<?php echo $listSubjects['id'].'#'.$listSubjects['subject_name']; ?>"> <?php echo $listSubjects['subject_name']; ?>
            </div>
        </td>
        <td scope="col">
            <input type="number" min="0" name="**subject_fee[]**" id="subject_fee" class="form-control" style="text-align:right;" placeholder="" value="0.00" >
        </td>
        <td scope="col">
            <select name="**lecturer[]**" id="lecturer" class="form-select">
                <option value="" selected>--</option>
<?php
        if(isset($listLecturers)){
            foreach($listLecturers as $mylistLecturers){
?>
                <option value="<?php echo $mylistLecturers['id'].'#'.$mylistLecturers['full_name']; ?>"><?php echo $mylistLecturers['full_name']; ?></option>
<?php
            }
        }
?>
            </select> 
        </td>
            <td scope="col">
                <input type="number" min="0" name="**lecturer_fee[]**" class="form-control" style="text-align:right;" placeholder="" value="0.00" >
            </td>
    </tr>
<?php
    }
}
?>
    </tbody>
</table>
<div style="text-align:right;"> 
    <button type="submit" name="btn_save" class="btn btn-primary">SAVE</button>
    <button type="reset" name="btn_reset" class="btn btn-secondary">Reset</button>
    <button type="button" name="btn_close" class="btn btn-danger">Close</button>
</div>

控制器代码(MyCourse.php)

for($i=0; $i<=$selected_material; $i++){
    if($i<$selected_material){
       $subject=explode('#',(string)$this->request->getPost('subject[' . $i . ']'), 2);
       $lecturer_details=explode('#',(string)$this->request->getPost('lecturer[' . $i . ']'));
      $Total_subject_fee = $this->request->getPost('subject_fee[' . $i . ']') + $this->request->getPost('lecturer_fee[' . $i . ']');

      $data_subject[] = [
            'course_id'=>$this->request->getPost('course_id'), 
            'course_name'  => $this->course_name, 
            'subject_id'=>$subject[0],
            'subject_name'  =>$subject[1],
            'subject_fee'  =>$this->request->getPost('subject_fee[' . $i . ']'),
            'lecturer_id'    =>substr((string)$this->request->getPost('lecturer[' . $i . ']'),0,1), 
            'lecturer_name'   =>$this->request->getPost('lecturer[' . $i . ']'), 
            'lecturers_fee'=>$this->request->getPost('lecturer_fee[' . $i . ']'),
            'total_subject_fee'  =>$Total_subject_fee,
            'status'  => '1',
            'session_id'  => session_id(),
            'created_by'  => 'xxx'
      ];

      var_dump($data_subject);
   }
}

$this->CourseModel->insertCourseSubjects($data_subject); // 调用模型方法

模型代码

public function insertCourseSubjects($data){
      $builder = $this->db->table("tbl_course_subjects");
      $builder->insertBatch($data);
      return true;
}

$data_subject数组输出

array(5) {
  [0]=>
  array(12) {
    ["course_id"]=>string(6) "000083"
    ["course_name"]=>string(15) "G-01 2023 batch"
    ["subject_id"]=>string(1) "1"
    ["subject_name"]=>string(5) "Tamil"
    ["subject_fee"]=>string(5) "10.00"
    ["lecturer_id"]=>string(1) "7"
    ["lecturer_name"]=>string(22) "7#Veerasingam Rajeevan"
    ["lecturers_fee"]=>string(4) "0.00"
    ["total_subject_fee"]=>float(10)
    ["status"]=>string(1) "1"
    ["session_id"]=>string(32) "m16pkq2qrb711c41siatpik4bd2s2mqr"
    ["created_by"]=>string(6) "Rajeev"
  }
  [1]=>
  array(12) {
    ["course_id"]=>string(6) "000083"
    ["course_name"]=>string(15) "G-01 2023 batch"
    ["subject_id"]=>string(1) "3"
    ["subject_name"]=>string(7) "History"
    ["subject_fee"]=>string(4) "0.00"
    ["lecturer_id"]=>string(0) ""
    ["lecturer_name"]=>string(0) ""
    ["lecturers_fee"]=>string(4) "0.00"
    ["total_subject_fee"]=>float(0)
    ["status"]=>string(1) "1"
    ["session_id"]=>string(32) "m16pkq2qrb711c41siatpik4bd2s2mqr"
    ["created_by"]=>string(6) "Rajeev"
  }
  [2]=>
  array(12) {
    ["course_id"]=>string(6) "000083"
    ["course_name"]=>string(15) "G-01 2023 batch"
    ["subject_id"]=>string(1) "6"
    ["subject_name"]=>string(8) "Religion"
    ["subject_fee"]=>string(5) "10.00"
    ["lecturer_id"]=>string(1) "8"
    ["lecturer_name"]=>string(29) "8#Shandramohan Shanmugaratnam"
    ["lecturers_fee"]=>string(5) "10.00"
    ["total_subject_fee"]=>float(20)
    ["status"]=>string(1) "1"
    ["session_id"]=>string(32) "m16pkq2qrb711c41siatpik4bd2s2mqr"
    ["created_by"]=>string(6) "Rajeev"
  }
  [3]=>
  array(12) {
    ["course_id"]=>string(6) "000083"
    ["course_name"]=>string(15) "G-01 2023 batch"
    ["subject_id"]=>string(2) "10"
    ["subject_name"]=>string(21) "Business & Accounting"
    ["subject_fee"]=>string(4) "0.00"
    ["lecturer_id"]=>string(0) ""
    ["lecturer_name"]=>string(0) ""
    ["lecturers_fee"]=>string(4) "0.00"
    ["total_subject_fee"]=>float(0)
    ["status"]=>string(1) "1"
    ["session_id"]=>string(32) "m16pkq2qrb711c41siatpik4bd2s2mqr"
    ["created_by"]=>string(6) "Rajeev"
  }
  [4]=>
  array(12) {
    ["course_id"]=>string(6) "000083"
    ["course_name"]=>string(15) "G-01 2023 batch"
    ["subject_id"]=>string(2) "13"
    ["subject_name"]=>string(5) "Music"
    ["subject_fee"]=>string(4) "0.00"
    ["lecturer_id"]=>string(0) ""
    ["lecturer_name"]=>string(0) ""
    ["lecturers_fee"]=>string(4) "0.00"
    ["total_subject_fee"]=>float(0)
    ["status"]=>string(1) "1"
    ["session_id"]=>string(32) "m16pkq2qrb711c41siatpik4bd2s2mqr"
    ["created_by"]=>string(6) "Rajeev"
  }
}

问题原因及修复方案

核心问题

  1. 表单字段索引不匹配:未勾选的checkbox不会被提交到后端,但控制器通过固定索引循环所有科目,导致尝试获取未勾选科目对应的讲师、费用字段时,索引错位,拿到空值。
  2. 讲师ID提取不严谨:用substr截取前1位获取讲师ID,若讲师ID为两位数会出错,且未处理讲师未选择的情况。

修复步骤

1. 修改视图:给表单字段绑定科目ID作为索引

确保勾选的科目与对应的讲师、费用字段一一关联:

<?php 
if(isset($listSubjects)){
    foreach($listSubjects as $subject){ 
?>
    <tr class="border border-secondary">
        <td scope="col">
            <div class="form-check">
                <input class="form-check-input" type="checkbox" name="subject[<?php echo $subject['id']; ?>]" value="<?php echo $subject['id'].'#'.$subject['subject_name']; ?>"> <?php echo $subject['subject_name']; ?>
            </div>
        </td>
        <td scope="col">
            <input type="number" min="0" name="subject_fee[<?php echo $subject['id']; ?>]" class="form-control" style="text-align:right;" placeholder="" value="0.00" >
        </td>
        <td scope="col">
            <select name="lecturer[<?php echo $subject['id']; ?>]" class="form-select">
                <option value="" selected>--</option>
<?php
        if(isset($listLecturers)){
            foreach($listLecturers as $lecturer){
?>
                <option value="<?php echo $lecturer['id'].'#'.$lecturer['full_name']; ?>"><?php echo $lecturer['full_name']; ?></option>
<?php
            }
        }
?>
            </select> 
        </td>
            <td scope="col">
                <input type="number" min="0" name="lecturer_fee[<?php echo $subject['id']; ?>]" class="form-control" style="text-align:right;" placeholder="" value="0.00" >
            </td>
    </tr>
<?php
    }
}
?>

2. 修改控制器:仅处理勾选的科目

遍历提交的subject数组,通过科目ID关联对应字段:

// 获取所有勾选的科目
$selectedSubjects = $this->request->getPost('subject');
$data_subject = [];

foreach($selectedSubjects as $subjectId => $subjectValue){
    // 拆分科目ID和名称
    $subject = explode('#', $subjectValue, 2);
    // 获取对应费用和讲师信息
    $subjectFee = $this->request->getPost('subject_fee[' . $subjectId . ']') ?? 0;
    $lecturerFee = $this->request->getPost('lecturer_fee[' . $subjectId . ']') ?? 0;
    $lecturerValue = $this->request->getPost('lecturer[' . $subjectId . ']');
    
    $Total_subject_fee = (float)$subjectFee + (float)$lecturerFee;
    
    // 处理讲师信息(兼容未选择的情况)
    $lecturerId = '';
    $lecturerName = '';
    if(!empty($lecturerValue)){
        $lecturerDetails = explode('#', $lecturerValue, 2);
        $lecturerId = $lecturerDetails[0];
        $lecturerName = $lecturerDetails[1];
    }
    
    $data_subject[] = [
        'course_id' => $this->request->getPost('course_id'), 
        'course_name' => $this->course_name, 
        'subject_id' => $subject[0],
        'subject_name' => $subject[1],
        'subject_fee' => $subjectFee,
        'lecturer_id' => $lecturerId,
        'lecturer_name' => $lecturerName,
        'lecturers_fee' => $lecturerFee,
        'total_subject_fee' => $Total_subject_fee,
        'status' => '1',
        'session_id' => session_id(),
        'created_by' => 'Rajeev'
    ];
}

$this->CourseModel->insertCourseSubjects($data_subject);

3. 模型代码无需修改

原模型的insertBatch逻辑正常,保持不变即可。


内容的提问来源于stack exchange,提问作者Veerasingam Rajeevan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 03:37:06