Codeigniter Delete Query with example
In this exam, we will discuss about how to delete a record or data (Codeigniter Delete Query with example) from the MySQL database using the CodeIgniter framework. so we can easily delete data into the database using the Delete Query method.
so you can see the following two ways for Codeigniter delete database record.
Without Use Model
In this step, first, we will load the database library in the controller or directly load in the “application/config/autoload.php” file and pass the data into a delete() Query method. so here we can directly pass data without a model. see following below example.
application/controller/Product.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Product extends CI_Controller { public function __construct() { parent::__construct(); $this->load->database(); } public function delete_product($id) { if($this->db->delete('product',array('id'=>$id))) { echo "Product has been successfully deleted"; } else { echo "Something Went Wrong"; } } } ?> |
With Use Model
In this step, first, we will load the database library in the model or directly load in the “application/config/autoload.php” file and pass the data into a delete() Query method. so you can see following below example.
application/controller/Product.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Product extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('product_model'); } public function delete_product($id) { $res = $this->product_model->delete_product('product', array('id' => $id)); if($res) { echo "Product has been successfully deleted"; } else { echo "Something Went Wrong"; } } } ?> |
application/models/Product_model.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Product_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } public function delete_product($table,$where) { if($this->db->delete($table,$where)) { return true; } else { return false; } } } ?> |