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

如何在CodeIgniter中通过表单同时向两张表插入数据?

嘿,这个需求在CodeIgniter里实现起来很直观,核心就是要保证两张表的数据插入逻辑要么都成功,要么都失败(避免出现一张表插入成功另一张失败的情况),所以推荐用数据库事务来处理。下面给你控制器和模型的具体实现方案:

控制器(Controller)实现

假设你的控制器名为FormController,处理表单提交的方法是submit_form。这里我们先做基础的表单验证,然后调用模型的插入方法:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class FormController extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // 加载模型
        $this->load->model('FormModel');
        // 加载表单验证库(按需使用)
        $this->load->library('form_validation');
    }

    public function submit_form() {
        // 自定义表单验证规则,根据你的实际字段调整
        $this->form_validation->set_rules('name', '姓名', 'required');
        $this->form_validation->set_rules('email', '邮箱', 'required|valid_email');
        $this->form_validation->set_rules('amount', '交易金额', 'required|numeric');

        if ($this->form_validation->run() === FALSE) {
            // 验证失败,返回表单页面并提示错误
            $this->load->view('form_view');
        } else {
            // 整理两张表需要的插入数据
            $main_table_data = [
                'name' => $this->input->post('name'),
                'email' => $this->input->post('email'),
                'created_at' => date('Y-m-d H:i:s')
            ];

            $fin_tran_data = [
                'amount' => $this->input->post('amount'),
                'tran_type' => 'deposit', // 示例交易类型,可按需修改
                'created_at' => date('Y-m-d H:i:s')
            ];

            // 调用模型的统一插入方法
            $insert_result = $this->FormModel->insert_to_two_tables($main_table_data, $fin_tran_data);

            if ($insert_result) {
                // 插入成功,跳转至成功页面或提示
                redirect('success_page');
            } else {
                // 插入失败,返回表单并提示错误
                $this->session->set_flashdata('error', '数据插入失败,请重试');
                $this->load->view('form_view');
            }
        }
    }
}
模型(Model)实现

这里用数据库事务来保证操作的原子性,确保两张表的插入要么都完成,要么都回滚:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class FormModel extends CI_Model {

    // 替换成你原来的主表名称
    private $main_table = 'your_main_table';
    // 交易表名称
    private $tran_table = 'fin_tran';

    public function insert_to_two_tables($main_data, $tran_data) {
        // 开启数据库事务
        $this->db->trans_start();

        // 1. 先插入主表
        $this->db->insert($this->main_table, $main_data);
        // 如果fin_tran需要关联主表的自增ID,获取这个ID
        $main_id = $this->db->insert_id();
        // 将主表ID添加到交易表数据中(按需使用,无关联可删除此行)
        $tran_data['main_id'] = $main_id;

        // 2. 插入交易表
        $this->db->insert($this->tran_table, $tran_data);

        // 完成事务,自动处理提交/回滚
        $this->db->trans_complete();

        // 检查事务执行状态
        return $this->db->trans_status() !== FALSE;
    }
}

补充说明:

  • 如果两张表没有关联关系,直接去掉$tran_data['main_id'] = $main_id;这一行即可。
  • 如果你想拆分方法,也可以在模型里写insert_main_table()和insert_fin_tran()两个独立方法,但一定要手动包裹事务,不然容易出现数据不一致的问题。
  • 记得替换代码中的your_main_table为你实际的主表名称,字段名也要根据数据库结构调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:28:25