Codeigniter Update Query Using Where Condition
In this article, we will discuss how to update a record or data (Codeigniter Update Query Using Where Condition) from the MySQL database using the CodeIgniter framework. so we can easily update data into the database using the Update Query method.
so you can see the following two ways for Codeigniter to update database records.
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 an update() Query method. so here we can directly pass data without a model. see the 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 25 | <?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 update_product($id) { $editData['title'] = $this->input->post('txtTitle'); $editData['category'] = $this->input->post('txtCategory'); $editData['description'] = $this->input->post('txtDescription'); $this->db->where('id', $id); if ($this->db->update('product', $editData)) { echo "Product has been successfully updated"; } 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 an update() 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 | <?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 update_product($id) { $editData['title'] = $this->input->post('txtTitle'); $editData['category'] = $this->input->post('txtCategory'); $editData['description'] = $this->input->post('txtDescription'); if ($this->product_model->update_product($editData,$id)) { echo "Product has been successfully updated"; } 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 | <?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 update_product($editData,$id) { $this->db->where('id', $id); if ($this->db->update('product', $editData)) { return true; } else { return false; } } } ?> |