2017-08-04 65 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']'也不起作用。 .. –