如何在CodeIgniter 3中同时插入数据库student_id与Excel导入数据?
问题描述
在CodeIgniter 3中使用Simplexlsx.class.php导入学生成绩到数据库,需求是从上传的Excel文件(仅包含学生成绩和教师备注行)读取数据,同时将从数据库student表获取的对应student_id同步插入目标表。目前执行后所有记录的student_id都固定为200,无法按预期对应不同学生。
预期结果表
| id | teacher_id | subject | student_id | marks | section_id |
|---|---|---|---|---|---|
| 1 | 23 | math | 200 | 70 | 7 |
| 2 | 23 | math | 201 | 73 | 7 |
| 3 | 23 | math | 202 | 72 | 7 |
| 4 | 23 | math | 203 | 76 | 7 |
| 5 | 23 | math | 204 | 78 | 7 |
| 6 | 23 | math | 205 | 80 | 7 |
获取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); }
当前结果表
| id | teacher_id | subject | student_id | marks | section_id |
|---|---|---|---|---|---|
| 1 | 23 | math | 200 | 70 | 7 |
| 2 | 23 | math | 200 | 73 | 7 |
| 3 | 23 | math | 200 | 72 | 7 |
| 4 | 23 | math | 200 | 76 | 7 |
| 5 | 23 | math | 200 | 78 | 7 |
| 6 | 23 | math | 200 | 80 | 7 |
问题分析与解决方案
核心问题
- 循环
foreach($query_data_student as $rows)每次都会覆盖$arr_student_id,最终只会得到最后一个学生的ID,导致所有记录用同一个ID。 - 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
相关产品推荐
相关产品推荐

