获取最后插入的id代码点火器并在视图中显示


Get the last inserted id codeigniter and display in view

大家好,我想获得最后插入的id并将其显示在我的视图中。

以下是我的代码,

控制器:

    $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);
    }

型号:

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

视图:

         <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>

但它只是显示0。我的代码出了什么问题?非常感谢您的帮助。谢谢

$this->db->insert_id();在插入代码之后使用,然后返回最后插入的id。

您可以使用$this->CustomersModel->db->select_max("id")->get('tableName');而不是$this->db->insert_id();