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

如何在CodeIgniter中向数据库插入发票数据?开发新手求助

别慌!作为刚接触CodeIgniter的新手,搞不懂怎么往数据库插发票数据太正常了,我带你一步步捋清楚,从数据库配置到代码实现全给你安排明白!

第一步:先搞定数据库连接配置

首先得让CodeIgniter能连上你的数据库,打开application/config/database.php文件,找到$db['default']配置数组,把占位符换成你自己的数据库实际信息:

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost', // 本地数据库一般填这个,远程的话填对应服务器地址
    'username' => 'your_db_username', // 你的数据库用户名,比如root
    'password' => 'your_db_password', // 数据库登录密码
    'database' => 'your_db_name', // 你要操作的数据库名称
    'dbdriver' => 'mysqli', // 常用的数据库驱动,保持这个就行
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

填完后保存,确保数据库服务是开启的,不然连不上哦。

第二步:创建发票数据表(如果还没有的话)

得先有个存发票数据的表,比如叫invoices,你可以用SQL语句在数据库里创建它:

CREATE TABLE invoices (
    id INT AUTO_INCREMENT PRIMARY KEY,
    invoice_number VARCHAR(50) NOT NULL UNIQUE, -- 发票编号,要唯一
    customer_name VARCHAR(100) NOT NULL, -- 客户名称
    total_amount DECIMAL(10,2) NOT NULL, -- 总金额,保留两位小数
    invoice_date DATE NOT NULL, -- 发票日期
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- 自动记录创建时间
);

如果需要更多字段(比如发票状态、备注),直接在这个SQL里加就行。

第三步:写处理数据库操作的模型(Model)

CodeIgniter是MVC架构,数据库操作最好放在模型里,这样代码更清晰。创建application/models/Invoice_model.php,内容如下:

<?php
class Invoice_model extends CI_Model {

    public function __construct() {
        parent::__construct();
        // 加载CI的数据库库,这样就能用内置的数据库方法了
        $this->load->database();
    }

    // 专门用来插入发票数据的方法
    public function insert_invoice($data) {
        // $data是一个关联数组,键对应表的字段名,值是要插入的数据
        return $this->db->insert('invoices', $data);
        // 插入成功返回TRUE,失败返回FALSE
    }
}
第四步:写控制器(Controller)处理请求

控制器用来接收数据(比如表单提交的内容),然后调用模型完成插入。创建application/controllers/Invoice.php:

<?php
class Invoice extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // 加载刚才写的发票模型
        $this->load->model('Invoice_model');
        // 加载表单验证库,用来校验提交的数据是否合法
        $this->load->library('form_validation');
    }

    // 显示发票录入表单(可选,如果你用网页表单提交的话)
    public function create() {
        $this->load->view('invoice_form');
    }

    // 处理表单提交,插入发票数据
    public function store() {
        // 设置表单验证规则,确保数据符合要求
        $this->form_validation->set_rules('invoice_number', '发票编号', 'required|is_unique[invoices.invoice_number]');
        $this->form_validation->set_rules('customer_name', '客户名称', 'required');
        $this->form_validation->set_rules('total_amount', '总金额', 'required|numeric');
        $this->form_validation->set_rules('invoice_date', '发票日期', 'required|valid_date');

        if ($this->form_validation->run() === FALSE) {
            // 验证失败,回到表单页面,显示错误信息
            $this->load->view('invoice_form');
        } else {
            // 整理要插入的数据,从表单POST中获取
            $invoice_data = array(
                'invoice_number' => $this->input->post('invoice_number'),
                'customer_name' => $this->input->post('customer_name'),
                'total_amount' => $this->input->post('total_amount'),
                'invoice_date' => $this->input->post('invoice_date')
            );

            // 调用模型的插入方法
            $insert_success = $this->Invoice_model->insert_invoice($invoice_data);

            if ($insert_success) {
                echo "发票数据插入成功!";
                // 也可以用redirect跳转到成功页面:redirect('invoice/success');
            } else {
                echo "插入失败,请检查数据库连接或数据格式!";
            }
        }
    }
}
第五步:写表单视图(View)(可选,用网页提交的话)

如果是通过网页表单录入发票,创建application/views/invoice_form.php:

<!DOCTYPE html>
<html>
<head>
    <title>录入发票</title>
</head>
<body>
    <h1>录入新发票</h1>
    <?php echo validation_errors(); ?> <!-- 显示表单验证的错误提示 -->
    <?php echo form_open('invoice/store'); ?> <!-- 表单提交到Invoice控制器的store方法 -->

    <label for="invoice_number">发票编号:</label>
    <input type="text" name="invoice_number" id="invoice_number" required><br><br>

    <label for="customer_name">客户名称:</label>
    <input type="text" name="customer_name" id="customer_name" required><br><br>

    <label for="total_amount">总金额:</label>
    <input type="number" step="0.01" name="total_amount" id="total_amount" required><br><br>

    <label for="invoice_date">发票日期:</label>
    <input type="date" name="invoice_date" id="invoice_date" required><br><br>

    <input type="submit" value="保存发票">

    <?php echo form_close(); ?>
</body>
</html>
一些新手友好的提示
  • 调试的时候可以打开CI的错误提示:在application/config/config.php里设置$config['debug'] = 1;,这样出问题能看到具体错误信息,方便排查。
  • 如果不是用表单提交,而是直接在代码里插测试数据,直接在控制器里构造$invoice_data数组,调用模型方法就行,不用写表单。
  • CI的数据库还有很多实用方法,比如批量插入insert_batch,你可以查看本地的CodeIgniter文档了解更多。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:24:23