In this tutorial you will learn about the CodeIgniter Delete Query and its application with practical example.
In CodeIgniter, delete() method is used to delete an existing record from database table. In order to generate delete statement, delete() method is used in following ways –
Syntax:-
1 |
delete($table = '', $where = '', $limit = NULL, $reset_data = TRUE) |
Here,
$table(mixed):- The table(s) to delete from. String or array
$where(mixed):- The where clause
$limit(mixed):- The limit clause
$reset_data(bool):- TRUE to reset the query “write” clause
Returns(mixed)
Example:- Let’s say you have a MySQL table named ’employee_master’ with the following fields –
emp_ID, emp_name, emp_email, emp_phone, emp_address, emp_code and emp_dept
Delete Record using $this->db->delete()
This is how you can delete a record from ’employee_master’ table using $this->db->delete().
1 2 |
$this->db->delete('employee_master', array('emp_ID' => $id)); //DELETE FROM employee_master WHERE emp_ID = $id |
1 2 3 |
$this->db->where('emp_ID', $id); $this->db->delete('employee_master'); //DELETE FROM employee_master WHERE emp_ID = $id |
An array of table names can be passed into delete() if you would like to delete record(s) from multiple tables.
1 2 3 |
$tables = array('table1', 'table2', 'table3'); $this->db->where('id', $id); $this->db->delete($tables); |
Delete All Records using $this->db->empty_table()
This is how you can delete all records from ’employee_master’ table using $this->db->empty_table().
1 2 |
$this->db->empty_table('employee_master'); // DELETE FROM employee_master |
Delete All Records using $this->db->truncate()
This is how you can delete all records from ’employee_master’ table using $this->db->truncate().
1 2 3 4 5 |
$this->db->from('employee_master'); $this->db->truncate(); (OR) $this->db->truncate('employee_master'); // TRUNCATE table employee_master; |
Delete With Join
1 2 3 4 |
$this->db->from("table1"); $this->db->join("table2", "table1.t1_id = table2.t2_id"); $this->db->where("table2.t2_id", $id); $this->db->delete("table1"); |