Codeigniter delete row from db
Solution 1
In Your HTML.... you should pass the user_id_to_delete
like this:
<a href="<?php echo site_url('admin/delete_row/'.$user_id_to_delete);?>">Delete</a>
Now, in the Controller
you should receive the user_id_to_delete
variable into the user_id
when it gets to the delete_row()
method. Now, you can send it as a HTTP post transaction.
public function delete_row($user_id) {
$this->load->model("model_admin");
$this->model_admin->did_delete_row($user_id);
}
For the model you will get the user_id
to delete. Here is the function for your admin model
public function did_delete_row($id){
$this -> db -> where('user_id', $id);
$this -> db -> delete('users');
}
Finally, update the delete URL line as follows:
<td><a href="<?php echo site_url('admin/delete_row/'.$user['user_id']);?">Delete</a></td>
That Should work for you
Solution 2
Codeigniter 3:
Use - $this->db->delete()
$this->db->delete('mytable', array('id' => $id)); // Produces: DELETE FROM mytable WHERE id = $id
OR - Delete from multiple tables:
$tables = array('table1', 'table2', 'table3');
$this->db->where('id', '5');
$this->db->delete($tables);
https://www.codeigniter.com/userguide3/database/query_builder.html
Related videos on Youtube
NiceTry
Updated on July 08, 2020Comments
-
NiceTry over 3 years
Just want to delete row from db table by passing id. Please help me to pass id from the view correctly. Any help will be highly appreciated. Please let me know if any detailed information is needed so that I can provide it.
Here is my Model:
public function did_delete_row($user_id){ $query = $this->db->get_where('users',array('user_id' => $user_id)); if ($query->num_rows() == 1) { if ($this->db->delete('users',array('user_id','email','name','city'))) {return true;} else {return false;} } else {return false;} }
Here is My view:
<a href="<?php echo site_url('admin/delete_row/'.$user_id);?">Delete</a>
Here is My controller:
public function delete_row($user_id) { $this->load->model("model_admin"); $this->model_admin->did_delete_row($user_id); }
-
Rahil Wazir almost 10 yearsYou can append the query string to your URL. Like:
/delete_row?id=1
. Then you can retrieve the id using$this->input->get('id');
-
NiceTry almost 10 yearsI have just edited my code. Could you check it now please?
-
Rahil Wazir almost 10 yearsThe delete accepts second parameter as associative array (
WHERE
clause). You need$this->db->delete('users',array('user_id' => $this->input->get('user_id')))
. Also you have semi colon;
in yourget_where
clause
-
-
NiceTry almost 10 yearsI changed my code as per your advice but it generates errors for controller code. I guess something is wrong with my view. I don't know if I pass id correctly.
-
Fisherman almost 10 yearsgive your view and controller code for generating the view
-
NiceTry almost 10 yearsI have just edited my question and added view and controller code for generating the view. Please have a look at it.