2014-04-26 51 views
1

你好傢伙我想獲取最後插入的id並將其顯示在我的視圖中。獲取最後插入的id codeigniter並在視圖中顯示

下面是我的代碼,

控制器:

$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.我的代碼有什麼問題?非常感謝幫助。謝謝。

回答

0

$this->db->insert_id();剛剛在插入代碼後面使用,然後它返回最後插入的ID。

可以使用$this->CustomersModel->db->select_max("id")->get('tableName');代替$this->db->insert_id();

+0

謝謝,我將如何顯示在我的看法? –

+0

試試這行$ data ['last_id'] = $ this-> CustomersModel-> db-> select_max(「id」) - > get('tableName');而不是$ data ['last_id'] = $ this-> db-> insert_id(); –

+0

是的,我把$ data ['last_id'] = $ this-> CustomersModel-> db-> select_max(「id」) - > get('tableName');在我的控制器中。我的問題是如何在我的視圖中顯示? –