CodeIgniter作为轻量级的PHP开发框架,内置了完善的数据库操作类,其中批量插入功能是处理多数据入库场景的常用工具,能够避免多次执行单条插入语句带来的性能损耗。

CodeIgniter批量插入基础用法
CodeIgniter的数据库类提供了batch_insert方法,专门用于实现批量插入操作,该方法属于Active Record模式的一部分,使用起来非常便捷。
首先需要加载数据库类,在控制器中可以通过以下方式加载:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test_controller extends CI_Controller {
public function __construct() {
parent::__construct();
// 加载数据库类
$this->load->database();
}
}
准备要插入的多条数据,数据格式为二维数组,每个子数组对应一条记录,键名需要和数据库表的字段名一致:
<?php
// 准备批量插入的数据
$insert_data = array(
array(
'username' => 'user1',
'email' => 'user1@ipipp.com',
'age' => 20
),
array(
'username' => 'user2',
'email' => 'user2@ipipp.com',
'age' => 22
),
array(
'username' => 'user3',
'email' => 'user3@ipipp.com',
'age' => 25
)
);
// 执行批量插入,第一个参数是表名,第二个参数是数据数组
$result = $this->db->batch_insert('user_table', $insert_data);
// 判断插入是否成功
if ($result) {
echo '批量插入成功,插入条数:' . $this->db->affected_rows();
} else {
echo '批量插入失败';
}
批量插入的注意事项
字段一致性要求
批量插入的二维数组中,每个子数组的键名必须和数据库表的字段名完全匹配,如果某个子数组缺少某个字段,且该字段在数据库中没有默认值,会导致插入失败。
数据量限制
虽然batch_insert支持批量插入,但如果单次插入的数据量过大,可能会超过数据库的最大允许包大小,此时可以将数据分批次插入:
<?php
// 假设$all_data是所有的待插入数据,每100条插入一次
$batch_size = 100;
$total = count($all_data);
for ($i = 0; $i < $total; $i += $batch_size) {
$batch_data = array_slice($all_data, $i, $batch_size);
$this->db->batch_insert('user_table', $batch_data);
}
批量插入的替代方案
如果因为特殊需求无法使用batch_insert方法,也可以手动拼接批量插入的SQL语句执行:
<?php
$sql = "INSERT INTO user_table (username, email, age) VALUES ";
$value_arr = array();
foreach ($insert_data as $item) {
$value_arr[] = "('" . $this->db->escape_str($item['username']) . "', '" . $this->db->escape_str($item['email']) . "', " . intval($item['age']) . ")";
}
$sql .= implode(',', $value_arr);
// 执行自定义SQL
$this->db->query($sql);
这种方式需要注意对插入数据进行转义,避免SQL注入风险,escape_str方法可以对字符串类型的数据进行安全转义。
批量插入结果判断
执行batch_insert方法后,返回值为布尔类型,true表示插入成功,false表示插入失败。如果需要获取插入的条数,可以使用$this->db->affected_rows()方法,该方法返回最后一次数据库操作影响的行数。
如果插入过程中出现错误,可以通过$this->db->error()方法获取错误信息,方便排查问题:
<?php
if (!$result) {
$error = $this->db->error();
echo '插入错误:' . $error['message'];
}
CodeIgniterbatch_insert数据库批量插入Active_Record修改时间:2026-07-06 18:48:20