Advertisement
Google Ad Slot: content-top
CodeIgniter MySQL Delete Data
Deleting data is a common operation in CRUD (Create, Read, Update, Delete).
In CodeIgniter, we can delete records using:
- Query Builder (Active Record) – recommended way
- Raw SQL Queries – when you need more control
🔹 Step 1: Load Database
Make sure the database is connected:
$autoload['libraries'] = array('database');
Or load manually in the controller:
$this->load->database();
🔹 Step 2: Delete a Record by ID
class DeleteController extends CI_Controller {
public function delete_user($id) {
$this->db->where('id', $id);
$this->db->delete('users'); // DELETE FROM users WHERE id=?
if ($this->db->affected_rows() > 0) {
echo "User deleted successfully!";
} else {
echo "No record found!";
}
}
}
👉 Example URL:
http://your-site/index.php/deletecontroller/delete_user/1
🔹 Step 3: Delete with Multiple Conditions
public function delete_inactive_users() {
$this->db->where('status', 0);
$this->db->where('email LIKE', '%@example.com');
$this->db->delete('users'); // DELETE FROM users WHERE status=0 AND email LIKE '%@example.com'
echo $this->db->affected_rows() . " inactive users deleted!";
}
🔹 Step 4: Delete All Records (Be Careful ⚠️)
public function delete_all_users() {
$this->db->empty_table('users'); // TRUNCATE TABLE users
echo "All users deleted!";
}
🔹 Step 5: Delete Using Raw SQL
public function delete_with_limit() {
$sql = "DELETE FROM users WHERE status = 0 LIMIT 5";
$this->db->query($sql);
echo "5 inactive users deleted!";
}
🔹 Step 6: Delete Using Form Input
public function delete_from_form() {
$id = $this->input->post('id');
$this->db->where('id', $id);
$this->db->delete('users');
echo "User with ID $id deleted!";
}
🔹 Example Output
Before delete:
ID: 3 | Name: Alex | Email: alex@example.com | Status: 0
After delete:
Record with ID 3 removed from database.