简体   繁体   中英

Get the last inserted id codeigniter and display in view

Hello guys I want to get the last inserted id and display it in my view.

Below are my codes,

Controller:

    $this->load->view('bootstrap/header');
    $this->load->model('CustomersModel');
    $data['query'] = $this->CustomersModel->viewallcustomers(); 
    $data['last_id'] = $this->db->insert_id();

    $this->load->library('form_validation');
    $this->form_validation->set_rules(array(
        array(
            'field' => 'c_fname',
            'label' => 'Customer Firstname',
            'rules' => 'required'
            ),
        array(
            'field' => 'c_lname',
            'label' => 'Customer Lastname',
            'rules' => 'required'
            )
    ));

    $this->form_validation->set_error_delimiters('<div class="alert alert-error">', '</div>');
    if(!$this->form_validation->run()) {
        $this->load->view('customer_form', $data);
    }

Model:

public function viewallcustomers()
{

    $this->db->select('*');
    $this->db->from('customers');
    #$this->db->join('customers', 'salesmonitoring.customer_id = customers.customer_id');
    #$this->db->order_by("salesmonitoring.sales_id", "desc"); 

    $query = $this->db->get();

    return $query->result();

}

View:

         <div class="control-group">
        <?php 
         $form_label_attributes = array('class' => 'control-label');
        echo form_label('Customer ID', 'customer_id', $form_label_attributes); ?>
        <div class="controls">
            <?php echo form_input(array('name' => 'customer_id', 'value' => $last_id, 'readonly' => 'true') ); ?>
        </div>
    </div>

But it's just displaying 0. What is wrong with my codes? Help is pretty much appreciated. Thanks.

$this->db->insert_id(); is used just after the insertion code then it returns last inserted id.

you can use $this->CustomersModel->db->select_max("id")->get('tableName'); instead $this->db->insert_id();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM