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

时间:2023-01-26 15:06:48

I'm trying to insert fields to a table and grab the id (assume that the table's PRIMARY KEY is AUTO INCREMENT). I need that record's auto incremental ID to be inserted in a second table. I can obviously return $this->db->insert_id() but how do I access the value in Controller thereafter?

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

I tried to define it in a variable and access in the controller but it didn't work.

我试图在变量中定义它并在控制器中访问但它不起作用。

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

Model:

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();

} 

1 个解决方案

#1


1  

Just save the id from the first insert - then use it in the second?

只需保存第一个插入的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();

} 

#1


1  

Just save the id from the first insert - then use it in the second?

只需保存第一个插入的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();

}