如何在CI3的insert_batch中插入非数组参数id_article与date?
实现方案:无需在批量数组中添加公共字段的批量插入
完全可以实现不用给批量插入数组的每个元素手动添加id_article和date字段,CodeIgniter 3的查询构建器提供了更简洁的方式来统一设置这些公共值:
方法:使用$this->db->set()统一绑定公共字段
你只需修改控制器代码,移除循环内给每个row_data添加id_article和date的逻辑,转而在执行insert_batch前用set()方法统一设置这两个字段的值,批量插入的每一条数据会自动带上这两个值。
修改后的控制器代码
public function insert_data() { // Processing uploaded images $config['upload_path'] = 'training_assets/image_training/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '1024'; // Maximum size allowed in KB $this->load->library('upload', $config); // Get the text field values $id_article = $this->input->post("id_article"); $date = $this->input->post('date', TRUE); // Initialize an array to hold the batch data $data = array(); foreach ($_FILES['images']['name'] as $key => $image) { $_FILES['userfile']['name'] = $_FILES['images']['name'][$key]; $_FILES['userfile']['type'] = $_FILES['images']['type'][$key]; $_FILES['userfile']['tmp_name'] = $_FILES['images']['tmp_name'][$key]; $_FILES['userfile']['error'] = $_FILES['images']['error'][$key]; $_FILES['userfile']['size'] = $_FILES['images']['size'][$key]; // Check if file upload is successful if ($this->upload->do_upload()) { $upload_data = $this->upload->data(); // Prepare row data for insertion (不再包含id_article和date) $row_data = array( 'question' => $this->input->post('question', TRUE)[$key], 'a' => $this->input->post('a', TRUE)[$key], 'b' => $this->input->post('b', TRUE)[$key], 'c' => $this->input->post('c', TRUE)[$key], 'd' => $this->input->post('d', TRUE)[$key], 'key' => $this->input->post('key', TRUE)[$key], 'img' => $upload_data['file_name'] ); // Add row data to the batch $data[] = $row_data; } else { echo "File upload failed for image $key."; } } // Insert data to database if (!empty($data)) { // 统一设置公共字段 $this->db->set('id_article', $id_article); $this->db->set('date', $date); // 执行批量插入 $this->db->insert_batch('tb_question', $data); } else { echo "No data to insert."; } redirect("question"); }
原理说明
CodeIgniter的set()方法会将指定的键值对绑定到后续的数据库操作中,执行insert_batch时,这些公共字段会自动追加到每一条待插入的记录里,替代了循环内重复赋值的冗余操作,代码更简洁易维护。
注意事项
- 确保
$id_article和$date的值合法有效:比如id_article对应的数据表中存在匹配记录,date格式符合数据库字段要求(如Y/m/d或Y-m-d,取决于你的表结构)。 - CodeIgniter会自动处理字段值的转义,无需手动操作,保证数据插入的安全性。
内容的提问来源于stack exchange,提问作者Mas'ud Al Hafiz
相关产品推荐
相关产品推荐

