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

如何在CodeIgniter中一次性向多张数据库表插入多行数据

使用CodeIgniter一次性向多张表插入多行数据

你这段代码的思路是完全可行的——借助CodeIgniter的insert_batch()方法实现单表批量插入,再通过循环依次切换目标表t1、t2、t3,最终完成多表批量插入的需求。先把你的代码整理成更易读的格式:

$data = array(
    array(
        'title' => 'My title',
        'name' => 'My Name',
        'email' => 'E-mail'
    ),
    array(
        'title' => 'Another title',
        'name' => 'Another Name',
        'email' => 'E-mail'
    ),
    array(
        'title' => 'Another title 2',
        'name' => 'Another Name 2',
        'email' => 'E-mail 2'
    )
);

$i = 1;
for($k = 0; $k < 3; $k++){
    $this->db->insert_batch('t'.$i++, $data);
}

不过这里有几个可以优化的点,让代码更健壮、灵活:

1. 避免硬编码表数量,用表名数组更清晰

如果后续表的数量或名称有变动,直接修改数组即可,不用调整循环次数,可读性也更强:

$tables = ['t1', 't2', 't3'];
$data = [/* 你的数据数组 */];

foreach ($tables as $table) {
    $this->db->insert_batch($table, $data);
}

2. 添加事务处理,保证数据一致性

如果其中某一张表插入失败,可能会导致部分表有数据、部分没有,开启数据库事务可以确保所有插入操作要么全部成功,要么全部回滚:

$tables = ['t1', 't2', 't3'];
$data = [/* 你的数据数组 */];

// 开启事务
$this->db->trans_start();

foreach ($tables as $table) {
    $this->db->insert_batch($table, $data);
}

// 完成事务
$this->db->trans_complete();

// 检查事务状态
if ($this->db->trans_status() === FALSE) {
    // 处理失败逻辑,比如记录错误日志或返回提示
    log_message('error', '多表批量插入操作失败');
}

3. 单独检查插入结果,方便排查问题

可以在循环里判断每个insert_batch的返回值,快速定位具体是哪个表插入出了问题:

$tables = ['t1', 't2', 't3'];
$data = [/* 你的数据数组 */];

foreach ($tables as $table) {
    $insertSuccess = $this->db->insert_batch($table, $data);
    if (!$insertSuccess) {
        $errorInfo = $this->db->error();
        log_message('error', "表 {$table} 插入失败:{$errorInfo['message']}");
        // 可根据业务需求选择中断循环或继续执行
        break;
    }
}

调整后的代码不仅更易维护,也能更好地应对异常情况~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:23:02