如何在CodeIgniter3中通过PHPExcel上传Excel更新MySQL数据
通过上传Excel文件更新MySQL数据库(PHPExcel实现)
你当前代码的核心问题是错误使用了批量插入方法而非批量更新,同时数据结构不符合批量更新的要求。以下是修正后的完整方案:
一、修正控制器代码
需要将Excel中读取的每行数据整合为包含id_follow_up(匹配条件)和tgl_fol_up(更新字段)的数组,无需单独维护$where数组:
public function import_excel(){ if(isset($_FILES["fileExcel"]["name"])){ $path = $_FILES["fileExcel"]["tmp_name"]; $object = PHPExcel_IOFactory::load($path); $temp_data = []; // 初始化数据数组 foreach($object->getWorksheetIterator() as $worksheet){ $highestRow = $worksheet->getHighestRow(); for($row=2; $row<=$highestRow; $row++) { // 读取日期并格式化为MySQL兼容格式 $tgl_fol_up = $worksheet->getCellByColumnAndRow(1,$row)->getValue(); $tgl_fol_up = PHPExcel_Style_NumberFormat::toFormattedString($tgl_fol_up, 'YYYY-MM-DD'); // 读取主键ID $id_follow_up = $worksheet->getCellByColumnAndRow(0,$row)->getValue(); // 构建批量更新所需的数组结构 $temp_data[] = [ 'id_follow_up' => $id_follow_up, 'tgl_fol_up' => $tgl_fol_up ]; } } $update = $this->Customer_list_model->update_import($temp_data); if($update) { $_SESSION['pesan'] = "Data Berhasil di Import ke Database"; $_SESSION['tipe'] = "success"; redirect($_SERVER['HTTP_REFERER']); }else{ $_SESSION['pesan'] = "Terjadi Kesalahan"; $_SESSION['tipe'] = "danger"; redirect($_SERVER['HTTP_REFERER']); } }else{ echo "Tidak Ada File yang masuk"; } }
二、修正模型代码
使用CodeIgniter的update_batch方法,该方法通过指定主键字段实现批量匹配更新:
public function update_import($temp_data) { // update_batch(表名, 数据数组, 用于匹配的主键字段名) $update = $this->db->update_batch('data_detail', $temp_data, 'id_follow_up'); return $update ? true : false; }
三、关键注意事项
update_batch逻辑:遍历数据数组,以每个元素的id_follow_up为匹配条件,将对应的tgl_fol_up更新到数据库中。- 确保Excel中的
Id_Follow_Up与数据库表的id_follow_up字段值类型、内容完全一致(比如均为整数),否则对应行不会被更新。 - 若Excel中存在数据库未记录的
Id_Follow_Up值,该行不会触发任何操作;如需同时新增数据,可额外判断后调用insert_batch补充。
内容的提问来源于stack exchange,提问作者Nings
相关产品推荐
相关产品推荐

