Hobby99
Hobby99

Reputation: 703

Codeigniter Updating database row by passing id in uri

I have an edit-button for each row in a list (view1). When that edit button gets clicked, a site opens where I can edit the row fields (view2). It passes the row's id to view2 correctly (id 11 in example below) which uri segment I call in the model to update this row 11 with array data from controller which array data I also passed to the model. But it still does not update. Thank you for your help.

(view 1):

//clicking edit button - redirects and passes row id 11 to view 2
<a href='<?= site_url("admin/admins/update_site/$admin->id") ?>'><img src='<?= base_url('media/admin/images/icons/config.png'); ?>'/></a>

(view 2):

// view 2 opens where I can edit the row fields 
//url is now: www.site.com/admin/admins/update_site/11:

<form action="<?= site_url('admin/admins/update'); ?>" method="POST">
    Username: <br>
    <input type='text' name='username'/><br>
    Password: <br>
    <input type='password' name='password' /><br>
    <input type='submit' name='submit' value='Save' />
</form>

controller:

//making an array with updated data and send it to the model
public function update(){
   $update = array(
        'username' => $this->input->post('username'),
        'password' => $this->input->post('password')
   );

  $this->load->model('admin/admins_model');
  $this->admins_model->update_admin($update);
  redirect(site_url('admin/admins/read'));
}

Model:

//update row 11 (from uri segment) the with the array data from controller 
public function update_admin($update){
    $this->db->where('id', $this->uri->segment(4));
    $this->db->update('admins', $update);
}

Upvotes: 1

Views: 6137

Answers (2)

DeiForm
DeiForm

Reputation: 664

Edit your routes so they will accept url like this: admin/admins/update/1 Then you can simply add parameter to your controller function update($id) so the $id will store 1. I suggest you to use for your route /(:num) to prevent non-numeric chars.

Upvotes: 1

Amin Adha
Amin Adha

Reputation: 316

i suggest u to add hidden field in ur form for id, problem here is ur form action dont have 4th segment.

view2:

<form action="<?= site_url('admin/admins/update'); ?>" method="POST">
    Username: <br>
    <input type='text' name='username'/><br>
    Password: <br>
    <input type='password' name='password' /><br>
    <input type='hidden' name='id' value="<?php $this->uri->segment(4) ?>"/>
    <input type='submit' name='submit' value='Save' />
</form>

model:

//update row 11 (from uri segment) the with the array data from controller 
public function update_admin($update){
    $this->db->where('id', $this->input->post('id'));
    $this->db->update('admins', $update);
}

Upvotes: 1

Related Questions