×

Update a Record CodeIgniter

Update a record

In this topic, we will learn how we can update existing records in database tables. To update a record, CodeIgniter provides an update() function used with the set() and where() functions as shown below:

  1. set(): As the name suggests, it is used to set the data to be updated in the database table.

Syntax

set($key [, $value = ‘’[, $escape = NULL]])

It has three parameters;

$key: It defines the fields name, or key/value pairs to be updated.

$value: It defines the fields value, if $key contain a single field.

$escape: This field defines, whether you want to escape value or an identifier.

  • where(): A where() function is used to determine the record to be updated in a database table.

Syntax

where($key [, $value = NULL [, $escape = NULL]])

It has three parameters:

$key: It contains the field names to be updated

$value: It contains the value of the field compared to the name of the key defined.

$escape: Determines whether to avoid values ??and identifiers.

  • update(): An update() function is used to update a single item received from a database.

Syntax

update([$table_name = “”[, $set = NULL [, $where = NULL[, $limit = NULL ]]]]) 

            It has four parameters:

            $table: The first parameter defines a table name.

$set (array): It defines an associative array that contains the fields value to be set in the database table.

$where (string): It defines a particular row to update.

$limit (int): It is used to set a limit in a database table.

 $records = array (
 ‘emp_id’ => ‘1’,
 ‘emp_name’ => ‘David’,
 ‘emp_des’ => ‘Manager’
 );
 $this->db->set($records);
 $this->db->where(“emp_id”, “1”);
 $this->db->update(“emp_tab”, $records); 

The following are the records of the employees table, that we must update data using the update() function, as shown in the image below.

To update the records in the database table, we need to create the following files, as shown below:

  1. Employee_controller.php
  2. Data_Model.php 
  3. update_view.php

Create a controller file Employee_controller.php and save it in application/controller/Employee_controller.php. And write the following program in the controller file.

Employee_controller.php

<?php
 defined('BASEPATH') OR exit( 'No direct script access allowed');
 class Employee_controller extends CI_Controller 
 {
  function _construct()
     {
         parent::_construct(); 
         $this->load->model('Data_Model'); // load model
         $this->load->library('uri'); // load uri library
     } 
 public function index() 
 {  
  $this->load->database();
     $this->load->model('Data_Model');
     $records['read_data'] = $this->Data_Model->read_data(); // read all data from table
   $this->load->view('fetch', $records); // display all fetch data
 }
 public function update_data() 
 {
     $this->load->database();
     $this->load->helper('form'); // load form helper
     $this->load->library('form_validation');  // load form_validation library
     $this->load->model('Data_Model');
     $id = $this->uri->segment(3); // get field id 
     $this->form_validation->set_rules('name', 'Full Name', 'required');
     $this->form_validation->set_rules('email', 'Email', 'required'); 
     $this->form_validation->set_rules('age', 'Age', 'required');
     $this->form_validation->set_rules('company', 'Company Name', 'required');
     $this->form_validation->set_rules('mob', 'Mobile No. ', 'required');
   $this->form_validation->set_rules('country', 'Country', 'required');
   if ($this->form_validation->run())
     {
         $this->load->model("Data_Model");   
         $records = array(       // receive data from update form 
             'name' => $this->input->post('name'),
             'email' => $this->input->post('email'),
             'age' => $this->input->post('age'),
             'company' => $this->input->post('company'),
             'mob' => $this->input->post('mob'),
             'country' => $this->input->post('country')
         );  
         if($this->input->post("update"))  /* if data receive from update view, update th record with primary id. */
         {  
             $this->Data_Model->update_id($records, $this->input->post("hidden_id"));
    redirect("Employee_controller/updated"); // transfer control to the updated function.
    }
 }
     else 
 {    
     redirect("Employee_controller/index"); // transfer to index function
    }        
                                                                                   
 } 
 public function updated()
 {   
  $this->load->library("form_validation"); // load form_validation library
     $records['message'] = 'Details has been successfully Updated';
 $this->load->view('update_view', $records); // shown updating details to the update_view 
 }
 // populate particular Id details of the employee
 public function update_id()
 {  
   $this->load->library("form_validation");
     $id = $this->uri->segment(3); // populate id
     $this->load->model("Data_Model");
          $records['user_data'] = $this->Data_Model->fetch_unique($id); // fetch details using id. 
     $records['read_data'] = $this->Data_Model->read_data(); // read all table data
     $this->load->view("update_view", $records);  // transfer details to update_view
 }
 }
 ?>     

Create a model file Data_Model.php and save it in application/model/Data_Model.php. And write the following program in the model file.

Data_Model.php

<?php
  class Data_Model extends CI_Model{
 public function __construct() {
 parent::__construct();
 $this->load->database();
 }
 public function read_data() 
 {
     $this->load->database();
 $this->db->select('*');
 $this->db->order_by('id', 'asc');
 $this->db->from("employees");
 $query = $this->db->get();
 return $query->result_array();
 } 
 public function fetch_unique($id)
 {
     $this->db->where("id", $id); // fetch particular id from table
     $query = $this->db->get("employees");
     return $query->result_array();
     //return $query;
 } 
 public function update_id($records, $id)
 {
     $this->db->where("id", $id);   update record to the selected id
     $this->db->update("employees", $records);
 }
 }
 ?> 

Create a view file update_view.php and save it in application/views/update_view.php. And write the following program in the view file.

update_view.php

<!DOCTYPE>
 <html>
 <head>
 <title>Tutorial and Example </title>
 </head>
 <body>
 <?php echo form_open('Employee_controller/update_data'); ?> 
 <div align="center"> <h2>Employee Update Form </h2></div>
 <fieldset width="80%">
 <legend>Details </legend>
 <p style="bgcolor:blue">  <?php if (isset($message)) { ?>
 <CENTER><h2 style="color:green;">Details has been successfully   Updated</h2></CENTER><br>
 <?php } ?> </p> 
 <table align="center" width="60%" border="0" bordercolor="green">  
 <?php
 if(isset($user_data))
 {
       foreach($user_data as $row)
       {
 ?>
 <input type="hidden"  name="hidden_id" value="<?php echo $row['id']; ?>"> 
 <tr><td align="left" valign="top" width="50%"> 
       Full Name :<span class="error" style="color:red">* </span></td>
       <td > <span style="color:red"> <?php echo form_error('name'); ?> 
 </span><input type="text" name="name" value="<?php echo $row['name'];  ?>" 
       style= "width:100%"placeholder="Enter the Name" 
       title="Please, Provide  Your Full Name !">   
 </td> </tr>
 <tr> <td align="left" valign="top" width="50%"> 
       Your Email-ID : <span class="error" style="color:red">* </span>  </td>
       <td > <span style="color:red"> <?php echo form_error('email'); ?> </span>
 <input type="email" name="email" size="30" value="<?php echo $row['email']; ?>" 
        style= "width:100%" placeholder="Enter the email id"
                   title="Please, Provide Your Personal Email-ID !">   
 </td> </tr>
 <tr>
 <td align="left" valign="top" width="50%">  
  Employee Age :<span style="color:red">*</span>:</td>
 <td > <span style="color:red"> <?php echo form_error('age'); ?> </span>
                    <input type="date" value="<?php echo $row['age']; ?>" 
       placeholder="Your Age....." name="age" style= "width:100%"; ></td></tr>
 <tr><td align="left" valign="top" width="50%">
       Company : <span class="error" style="color:red">* </span> </td>
 <td > <span style="color:red"> <?php echo form_error('company'); ?>  </span> 
 <input type= "text" placeholder= "Enter the Organization name"  name="company" value="<?php echo $row['company']; ?>"  
       style= "width:100%" title="Only Current company name"> 
 </td></tr>
 <tr><td align="left" valign="top" width="50%">
       Mobile No. :<span class="error" style="color:red">* </span>  </td>
       <td > <span style="color:red"> <?php echo form_error('mob'); ?> </span>
 <input type="number" name="mob" value="<?php echo $row['mob']; ?>" style= "width:100%" 
 placeholder="83685********" title="Please, Provide only Your Personal Contact Number !">          
 </td> </tr> 
 <tr><td align="left" valign="top" width="50%">
       Country :<span class="error" style="color:red">* </span> </td>
       <td > <span style="color:red"> <?php echo form_error('country'); ?> </span>
  <input type="text" name="country" style= "width:100%" value="<?php echo $row['country']; ?>" placeholder="Enter the country name" > 
 </td></tr>
 </table>
    <div align="center"> <input type="submit" value="Update" name="update"  style="color:Blue" /> 
 <input type="reset" value="RESET" ></div>
 <?php
       }
 }
 ?>
 </fieldset>
 <?php echo form_close(); ?>
 </body> 
 <div class="container"> <p> <b> <?php echo anchor('Employee_controller', 'See  Update'); ?> </b> </p> </div>
 </html> 

To run the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/index.php/Employee_controller function; It shows the output as shown below.

Now click on any edit link, it redirects you to the update form, as shown below. Suppose, we clicked on the Edit link of the Id no. 5, it redirects and receives all the details of the Id no.5 in the Employee Update Form, as shown in the below image.

Now update some fields of the Id no5.

For Example:

Ms Maeve to Ms Maeve Wiley,

maeve@gmail.com to maevewiley@gmail.com

After updating the details, click the update button, and then, it displays a successful message, as shown in the image below.

If you want to check, that your details have been updated in your main (Employee_controller) page, click on the See Update link, it redirects you to the main Controller page, as shown below.

And you can also verify the update details in the phpMyAdmin database, as shown in the image below.


Related Topics

CodeIgniter Models

Models are the classes that deals with backend operations. It is used to fetch the data from the database and send it to the Controller. All the database related information provided inside...

5 minutes read.

CodeIgniter Email Class

CodeIgniter provides an e-mail library that helps to send a message from one application to another. You can create and send text messages easily in CodeIgniter application even you can set email...

9 minutes read.

Form Validation Library Codeigniter

Form Validation Library The Codeigniter provides a form validation library that contains predefined rules to validate the form fields. It also helps in optimizing the form validation code, which reduces the effort and time...

31 minutes read.

CodeIgniter User Agent Class

User Agent Class The CodeIgniter provides a user agent class that helps to identify and collect information about the browser, mobile devices, or robots visiting your site. Besides this, it is also used...

4 minutes read.

CodeIgniter Output class

Output class The CodeIgniter framework contains a core class that is an Output class. It  includes the various functions that are used to send the final web page to the requesting browser. In...

8 minutes read.

HTML Table Class CodeIgniter

HTML Table Class The CodeIgniter framework provides an HTML Table Class that is used to develop an auto-generated table using a defined array or result sets of the database table. Loading an HTML Table Class...

8 minutes read.

CodeIgniter Smiley Helper

The smiley helper file contains smiley images that are used in the application for showing emotions and comments while chatting with others. Load a Smiley Helper Before using Smiley Helper in the CodeIgniter application, you...

4 minutes read.

Update a Record CodeIgniter

Update a record In this topic, we will learn how we can update existing records in database tables. To update a record, CodeIgniter provides an update() function used with the set()...

10 minutes read.

Calendaring Class CodeIgniter

Calendaring Class The calendar library contains various functions that are used to create a dynamic calendar. It also enables you to pass the data to calendar cells and 100% control over the calendar...

6 minutes read.

CodeIgniter Number helper

The number helper file contains some predefined function that deals with numeric data to display numbers in bytes format. Load a Number Helper You must load a number helper file in the controller to perform...

3 minutes read.

CodeIgniter Input Class

Input Class The CodeIgniter framework provides an input class that includes various input functions to pre-process global input data for protection; furthermore, it also provides some helper functions to obtain input data. This...

11 minutes read.

Codeigniter Session Library

Session Library The session is an essential part of any application. It contains various functions to manage the users' status and track their activity while browsing on the site. For example,...

13 minutes read.

CodeIgniter Encrypt Class

The Codeigniter provides an encrypt class used to protect confidential data stored on computer systems or data transmitted over a network. It provides two-way data encryption techniques such as Mcrypt PHP extension and...

4 minutes read.

CodeIgniter Views

A View is a presentational part which shows the information to the users. It is a complex web page which contains navbar, header, footer, sidebar, etc. A view file cannot be called directly...

5 minutes read.

CodeIgniter URL Helper

The helper file contains some predefined functions that are used to work with URL, such as generate the current file path, transfer control, redirect, create a link, etc. Load the URL Helper Before using...

7 minutes read.

CodeIgniter Date helper

A date helper file contains some predefined functions that work with date functions. Before using the date function in CodeIgniter, you have to load the date helper in the controller. For example: $this->load->helper(‘date’); Functions of...

12 minutes read.

CodeIgniter Libraries

The library is an important part of the CodeIgniter framework. It has a large collection of libraries files that are used to increase the performance of an application. By default, all CodeIgniter libraries...

4 minutes read.

CodeIgniter Text Helper

The text helper contains the various function that is used to operate with text such as define a word limit and characters limit, conversion of word from ASCII to entities, etc. Loading the text...

4 minutes read.

CodeIgniter Helpers

The Helpers (functions) are stored in the Helper file. It helps CodeIgniter to perform different tasks. The helper file is the collection of many functions that is used to perform specific task. It...

3 minutes read.

CodeIgniter Inflector Helper

The inflector helper file contains some predefined function that allows users to change their English words into plural, singular, and camel case, etc. Loading an Inflector Helper Before using an inflector helper function, you must...

3 minutes read.