Codeigniter 3: pre-populate update form with data from the database

I am making a “Customers” CRUD application in CodeIgniter 3. I have an update form that I want to pre-populate with the data corresponding to the customer, already existent in he database.

The model looks like this:

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

The controller looks like this:

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

In the view file (update.php) I have:

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

The customer’s first_name, although existent in the the database column called “first_name” does not pre-populate the form.

Summary:

If, in the view, I do <?php echo $customer->first_name; ?> it outputs the first-name correctly.

On the same view file 'value' => set_value($customer->first_name) outputs nothing.

Why is this?

It looks as though the method only returns the first row.

Try returning and using $query.

Edit:
From memory I think the return value should be $query->result();

Check the manual.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.