php - CodeIgniter:如何将 $this->db->insert_id() 值传递给 Controller 以便插入到另一个表中?

标签 php mysql codeigniter xampp

我正在尝试向表中插入字段并获取 ID(假设表的主键是 AUTO INCREMENT)。我需要将该记录的自动增量 ID 插入到第二个表中。我显然可以返回 $this->db->insert_id() 但我如何在之后访问 Controller 中的值?

我尝试在变量中定义它并在 Controller 中访问,但没有成功。

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: insert_id
Filename: controllers/POS.php
Line Number: 87

型号:

function populate_pos_purchase_table($posPurchase) {
    $this->db->trans_begin();
    $this->db->insert('pos_purchase', $posPurchase);

    if ($this->db->trans_status() === FALSE) {
        $this->db->trans_rollback();
        return false;
    }
    else {
        $this->db->trans_commit();
        $insert_id = $this->db->insert_id();
        return $insert_id;
        return true;
    }
}

Controller :

function update_payment_details() {

$newPayment = array (
    'pos_id' => $insert_id, // Line Number: 87
    'payment_description' => 'Point of Sales',
    'payment_method' => $this->input->post('payment_method'),
    'payment_date' => $this->input->post('payment_date'),
    'paid_amount' => $this->input->post('total'),
    'due_amount' => 0
);

$this->pos_model->populate_new_payment_table($newPayment);  
$this->index();

} 

最佳答案

只需保存第一个插入的 ID - 然后在第二个插入中使用它?

function update_payment_details() {

$insert_id = populate_pos_purchase_table($posPurchase);

$newPayment = array (
    'pos_id' => $insert_id, // Line Number: 87
    'payment_description' => 'Point of Sales',
    'payment_method' => $this->input->post('payment_method'),
    'payment_date' => $this->input->post('payment_date'),
    'paid_amount' => $this->input->post('total'),
    'due_amount' => 0
);

$this->pos_model->populate_new_payment_table($newPayment);  
$this->index();

} 

关于php - CodeIgniter:如何将 $this->db->insert_id() 值传递给 Controller 以便插入到另一个表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17574681/

相关文章:

php - SQL 查询中的变量被视为列

php - fetchAll 卡住了

php - 我必须为特定记录添加一些行..我的项目正在运行..所以我可以重做整个数据库

php - 如何使用 PHP 通过 AJAX 从 MySQL 数据库更新数据?

MySQL 或 MongoDB 数百万行降序排列

php - Codeigniter 3 fatal error : Call to a member function database() on null

php - 使用 CodeIgniter 从 MySQL 数据库检索图像,而不使用上传库。是否可以?

php - 如何在不编码的情况下使用 Volley 进行多部分?

php - 为什么sql无限加载数据?

mysql - 在MySQL查询中获取日期所在的单元格值