In this tutorial, we are going to learn CodeIgniter database delete operation. Sometimes We have a requirement to delete data in particular situations. In this case, we have to use conventional methods in which we have to create a connection each time whenever we have to delete any record within the database and close that connection after processing.

With the help of CodeIgniter active record database pattern we have delete method which will optimize our code. We just have to pass the name of table l from which we want to delete the record and the primary key of that record which we want to delete.

In the following example, you can observe we are going to delete a record having  “user_id = 1” in “user” table.

$this->db->delete('user', array('user_id' => 1));

We can also use where the method of active record with the delete method. Even that you can create a chain of methods such as the first place “where” method and then “delete” method. You will observe them as follows.

$this->db->where('user_id', 1);


$this->db->where('user_id', 1)->delete('user');

There is a point which you need to understand. In the above code, you have observed we have used only one “where” method by which we are just filtering record on one parameter.

Delete Record on Multiple Parameters 

If you want to filter record on multiple parameters such as:

Delete user WHERE user_id = 1 AND user_name = 'TutorialPace'

Then you can use multiple “where” methods like we have used in the below code for above logic.

$this->db->where('user_id ', 1);
$this->db->where('user_name ', 'TutorialPace');

Delete Record from Multiple Tables

There is another question regarding the deletion like what to do when someone wants to delete the data from multiple tables having the same where clause.

The simple solution is that we can store the name of the table within an array and pass that array in the place of table names like we have done in the following code.

$tables = array('users', 'users_log');
$this->db->where('user_id ', 1);
$this->db->where('user_name ', 'TutorialPace');

Delete All Record of Table

If you want to delete the table, CodeIgniter provides two methods which will give you the same results. You can use either “truncate” method or “empty_table” method to delete all records of the table.