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

如何在CodeIgniter 3中同时插入数据库student_id与Excel导入数据?

问题描述

在CodeIgniter 3中使用Simplexlsx.class.php导入学生成绩到数据库,需求是从上传的Excel文件(仅包含学生成绩和教师备注行)读取数据,同时将从数据库student表获取的对应student_id同步插入目标表。目前执行后所有记录的student_id都固定为200,无法按预期对应不同学生。

预期结果表

idteacher_idsubjectstudent_idmarkssection_id
123math200707
223math201737
323math202727
423math203767
523math204787
623math205807

获取student_id的查询语句

$section = $this->input->post('section-id');
$query_data_student = $this->db->select('student_id')
                               ->from('student')
                               ->where('section_id', $section)
                               ->order_by('name', 'ASC')
                               ->get()
                               ->result_array();

当前导入循环代码

foreach( $xlsx->rows() as $r ) {
    // 忽略Excel文件的首行标题
    if ($f == 0){ 
        $f++;
        continue;
    }
    /**不确定此foreach循环是否有效**/
    foreach($query_data_student as $rows){
       $arr_student_id = $rows['student_id'];
    }
        
    for( $i=2; $i < $num_cols; $i++ ){ 
       if ($i == 2) $data['marks']         = $r[$i];
       else if ($i == 3)    $data['notes'] = $r[$i];
    }
    $data['student_id'] = '200'; //曾尝试替换为$arr_student_id; **//问题所在:希望此值来自student表的student_id**
    $data['subject_name']   = $this->input->post('subject');
    $data['teacher_id'] = $this->input->post('teacher_id');
    $this->studentMarking_model->save($data);
}

当前结果表

idteacher_idsubjectstudent_idmarkssection_id
123math200707
223math200737
323math200727
423math200767
523math200787
623math200807

问题分析与解决方案

核心问题

  1. 循环foreach($query_data_student as $rows)每次都会覆盖$arr_student_id,最终只会得到最后一个学生的ID,导致所有记录用同一个ID。
  2. Excel行数据和student_id数组没有按索引对应,无法实现一行成绩对应一个学生ID。

修正后的代码

// 先把student_id提取为一维数组,方便按索引调用
$student_ids = array_column($query_data_student, 'student_id');
$f = 0;
// 同时遍历Excel行和student_id数组,用索引对应
foreach( $xlsx->rows() as $index => $r ) {
    // 忽略首行标题
    if ($f == 0){ 
        $f++;
        continue;
    }
    // 跳过超出student_id数组长度的行(防止数组越界)
    if (!isset($student_ids[$index - 1])) {
        continue;
    }
        
    $data = [];
    // 读取Excel中的成绩和备注
    if (isset($r[2])) $data['marks'] = $r[2];
    if (isset($r[3])) $data['notes'] = $r[3];
    
    // 对应索引的student_id
    $data['student_id'] = $student_ids[$index - 1]; 
    $data['subject_name'] = $this->input->post('subject');
    $data['teacher_id'] = $this->input->post('teacher_id');
    $data['section_id'] = $section; // 补充section_id,和预期结果表对应
    
    $this->studentMarking_model->save($data);
}

关键说明

  • 用array_column把查询到的二维student_id数组转成一维数组,格式如[200,201,202,...]。
  • 遍历Excel行时用$index记录当前行号,因为跳过了首行(索引0),所以对应student_ids的索引是$index - 1。
  • 增加数组越界判断,避免Excel行数多于学生数时报错。
  • 补充section_id字段,与预期结果表结构匹配。

内容的提问来源于stack exchange,提问作者harmoni creative

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:02:46