1

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?

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
    In your model, a function cannot return twice back-to-back like that. See the docs php.net/manual/en/function.return.php. "If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file." Commented Jul 10, 2013 at 15:39

1 Answer 1

1

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

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

} 
Sign up to request clarification or add additional context in comments.

1 Comment

Yup! $insert_id = $this->pos_model->populate_pos_purchase_table($posPurchase); worked in the Controller. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.