2017-08-04 63 views
0

UPDATE數據預填充更新形式:從數據庫

如果,在視圖中,我<?php echo $customer->first_name; ?>它正確地輸出第一名。

在相同的視圖文件'value' => set_value($customer->first_name)什麼都不輸出。


我在做笨3.一個「客戶」 CRUD應用程序,我有一個更新形式,我想對應的客戶數據,以預填充,已經在他的數據庫存在。

的模型看起來像這樣:

class Customer extends CI_Model { 
    /*Lots 
    of 
    code*/ 

public function getAllCustomers($customer_id) { 
    $query = $this->db->get_where('customers', array('id' => $customer_id)); 
    if ($query->num_rows() > 0) { 
     return $query->row(); 
    }  
    } 
} 

控制器看起來像這樣:

class Home extends CI_Controller { 

/*Lots 
    of 
    code*/ 

public function edit($customer_id){ 
    $this->load->model('Customer'); 
    $customer = $this->Customer->getAllCustomers($customer_id); 
    $this->load->view('update', ['customer'=>$customer]); 
} 
} 

在視圖文件(update.php)我有:

<?php echo form_input('first_name', '', [ 
      'type' => 'text', 
      'id' => 'first_name', 
      'class' => 'form-control', 
      'value' => set_value($customer->first_name), 
      'placeholder' => 'First name', 
    ]); 
?> 

的客戶的first_name,儘管存在於名爲「first_name」的數據庫列中並未預先填充表單。

這是爲什麼?

回答

0

這是如何做到這一點:

<?php echo form_input('first_name', set_value('first_name', $customer->first_name),[ 
    'id' => 'first_name', 
    'class' => 'form-control' 
    ]); 
?> 
0

總是使用$this->db->last_query()檢查您的查詢執行正確 如果last_query()不列入返回任何調試確保您所設定的'save_queries' => TRUEapp/config/database.php

查詢可能返回多個結果

改變你的模型像這樣

public function getAllCustomers($customer_id) { 
    $q = $this->db->get_where('customers', array('id' => $customer_id)); 
      log_message("error",$this->db->last_query()); //use this to get the complied query for debugging purpose 
     if ($q->num_rows() > 0) { 
       foreach (($q->result()) as $row) { 
        $data[] = $row; 
       } 
       return $data; 
      } 
      return FALSE; 
} 

如果您確定您的查詢可能只返回一個結果,請檢查$customer_id在數據它

public function getAllCustomers($customer_id) { 
    if($customer_id){ 
    $q = $this->db->get_where('customers', array('id' => $customer_id),1); //specify the limit if you want to get only one row 
      log_message("error",$this->db->last_query()); //use this to get the complied query for debugging purpose 
     if ($q->num_rows() > 0) { 

       return $q->row(); 
      } 

     } 
      return FALSE; 

} 
+0

'消息:試圖讓行19'線19個非對象的屬性是'「值」 => SET_VALUE( $ customer-> first_name),' –

+0

可能不是它的'stdobject'它的一個數組嘗試訪問這個名字,像這樣:$ customer ['first_name']' –

+0

'$ customer ['first_name']'也不起作用。 .. –