×

Migration Class CodeIgniter

The CodeIgniter framework provides the migration class that helps the web developers to create and handle databases in a structured and streamlined manner. The migration classes are very useful when more than one developer is working on the same project. If any developer has created a migration file or changed a database query, the developer must notify the other to run the migration file. It tracks information based on past history in migration and what changes are needed to run against production machines the next time you deploy it.

Database table migration is used to track which migration is already running and which files are required to update in your application. So, call $this->migration->current() function that helps which migration version should be run. And the current migration version is found in the application/config/migration.php.

Loading a Migration Class

Like other libraries in the CodeIgniter application, you must load a migrate class in the Controller file such as:

Syntax

 $this->load->library(‘migrate’);

Once the class is loaded, you can use a migrate object as shown:

  $this->migrate  

Type of the Migration file

There are two ways to use the migration files name:

  1. Sequential: As the name defines, a sequential filename begins with 001 (numeric), and each number must contain three digits with a string name and no gaps between them. For example, 001_add_data.php.
  2. Timestamp: Each migration filename uses a timestamp that follows the YYYYMMDDHHIISS format. It also helps to track the information at which time the database file was changed. Example 20201031104401_add_data.php is the migration file name.

Note: If you have selected a migration file type using a timestamp and created a file with a sequential format, the migration file will execute, but no table is created in the database.

How to get a timestamp in Codeigniter?

If you want to get timestamp data, you have to follow the syntax as shown below:

echo date('ymdhis'); And execute this statement in the controller, and then it shows the result- 200417020541.

Migration Method name

         There are two methods available in the Migration class:

  1. up() method: The up () method is used in the migration file to indicate what should be created when the migration file is run in the application.
  2. down() method: A down() method is the opposite of the up() method, which is used to undo all the operation that performed during the up() method. For example, suppose you have created a student table using the up() method, and if you want to undo all the changes in the migration file, you can use down() method.

To set a Migration

You need to know that the Codeigniter contains a migration file that is stored in the application/config/migration.php file. In that file, you need to make small changes to run the migration file such as:

Step1. By default, a migration file is disabled for security purposes. So, when you are going to use a migration file, set $config[‘migration_enabled’] to TRUE, and when its work has been finished, again set it to False.

Step2. You can set migration type in two ways –

  1. Set $config[‘migration_type’] = ‘timestamp’ as 201410311028_add_emp.php,
  2. Or set it $config[‘migration_type’] = ‘sequential’ as 001_add_emp.php

Stpe3. $config[‘migration_table’] = ‘migrations’. By default, the table name is migrations that keeps the current status of the table defined in the database. It also allows you to rename migration tables.

Step4. $config[‘migration_auto_latest’]: It defines whether you want to update the migration to the latest version.

Step5. $config[‘migration_version’] = 0; It defines the migration version of the file and if you are using a timestamp, you must pass a timestamp value such as, $config[‘migration_version’] = 200417020541;

Step6. $config[‘migration_path’]: It defines where the migration file should be placed in the codeigniter application. By default, it uses $config[migration_path’] = APPPATH.’migrations/’; Therefore, if you have not ‘migrations’ folder in your Codeigniter, you must create this directory under the application folder, as shown below.

Migration Class CodeIgniter

Now create a 200417020541_create_student.php file and save it to the following path application/migrations/200417020541_create_student.php folder. After that, write the following program in the migration file.

200417020541_create_student.php

<?php
 defined(' BASEPATH ') OR exit('No direct script access allowed');
 class Migration_Create_students extends CI_Migration 
 {
     public function up()
     {   
         $this->load->database(); 
         $this->dbforge->add_field(array(
             'stud_id' => array(
                     'type' => 'int',
                     'constraint' => 3,
                     'unsigned' => TRUE,
                     'auto_increment' => TRUE 
             ),
             'stud_name' => array(
                     'type' => 'varchar',
                     'constraint' => '100', 
             ),
             'stud_email' => array(
                 'type' => 'varchar',
                 'constraint' => '100',
         ),
             'stud_course' => array( 
                     'type' => 'varchar',
                     'constraint' => '100'
             ),
             'stud_address' => array(
                 'type' => 'varchar',
                 'constraint' => '100',
         ), 
     ));
     $this->dbforge->add_key('stud_id', TRUE); // add stud_id as a primary key
     $this->dbforge->create_table('students', TRUE); // create students table
 }
 }
 ?> 

Create a Migration_controller.php controller file and save it to the following path application/controller/Migration_controller.php folder. After that, write the following program in the controller file.

Migration_controller.php

<?php
 defined(' BASEPATH ') OR exit('No direct script access allowed');
 class Migration_controller extends CI_Controller
 {
         public function index()
         {    
               echo "<title> Tutorial and Example </title>"; 
                 $this->load->library('migration'); // load migration library
                 if ($this->migration->current() === False)
                 {
                         show_error($this->migration->error_string()); /* if current version is not found, it returns an error message. */
                 }
                 else
                 { 
                     echo "<h2> Migration table has been created </h2>";
                 }
         }
 }
 ?> 

To run the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/index.php/Migration_controller/add function; it shows the output,as shown below.

Migration Class CodeIgniter

If you want to check that your table is created in the database or not, go to phpMyAdmin and select the database that you provided during the creation of the migration file and then, you will see the image below.

Migration Class CodeIgniter

In this image, there are two tables: - migrations and students.

A migrations table that contains the version of the migrated table in the database, as shown below.

Migration Class CodeIgniter

Whereas, the table of students shows the structure of the table as defined in the file 200417020541_create_student.php. You can also check the structure of the students table by clicking on the database table that shows the image below.

Migration Class CodeIgniter

Delete table from the Database:

If you want to delete the migration table, create a Migration_controller.php file in the application/controllers folder and write the following program as shown below:

Migration_controller.php

<?php
 defined(' BASEPATH ') OR exit('No direct script access allowed');
 class Migration_controller extends CI_Migration 
 {
 public function down()
         {
         echo "<title> Tutorial and Example </title>"; 
         $this->load->library('migration'); // load migration class
         $delete_table = $this->dbforge->drop_table('students'); // pass the table name
         if($delete_table == true)
         {
         echo "Your table has been successfully deleted ";
         }
         else 
         {
                 echo "Table is not deleted";
         }
         }
 }
 ?> 

To run the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/index.php/Migration_controller/down; it shows the output,as shown below.

Migration Class CodeIgniter

You can also see if the table of students has been removed from the database. In that database, you will find only the migration table which stores the version number and the last update details, which is given below.

Migration Class CodeIgniter

Class References:

There are various class references available in the migration class:

  1. current(): As the name suggests, it is used to show the current version of the migration file that is set to $config["migration_version"] in application/configuration/migration.php.
  2. error_string(): As the function defines, it is used to display an error message that was detected while running the migration file.
  3. find_migrations(): A find_migration () function is used to return all migration files in the array format that found in the migration_ path.
  4. latest(): It works similar to the current () function except that it returns the latest string version on the success of the migration found in the filesystem.
  5. version(): A version() function is similar to current(), except that it is used to set the specific version to a migration file.

Syntax

$this->migration->version(6); 

Related Topics

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 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.

Installation of CodeIgniter

Before installing CodeIgniter, you need to make sure that the wamp or xampp server in the system is preinstalled. The installation procedure for CodeIgniter is very easy. You can download CodeIgniter by following these...

2 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.

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 Pagination Class

Pagination Class The CodeIgniter framework provides a pagination class that is used in the data list to create pagination links in a web application. Generally, it is used to retrieve data records from...

10 minutes read.

CodeIgniter URI Class

URI Class The CodeIgniter contains a URI class that is used to retrieve information from URI strings. It also provides suitability to get information from the re-routed segments. The system automatically initializes this...

6 minutes read.

CodeIgniter Security Class

Security Class The security class provides various function that helps to create a secure application and process input data securely to the application. This class is preloaded in the CodeIgniter application, so you...

4 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 Tutorial

What is CodeIgniter? CodeIgniter is an open-source framework for developing a dynamic web application with the use of PHP. It uses the MVC framework to develop the project, which is much...

3 minutes read.

Image Manipulation Codeigniter

Image Manipulation A Codeigniter provides an image manipulation class that is used for resizing, cropping, rotation, and many other manipulation tasks. This class also support three major image libraries such as GD/GD2, NetPBM, and...

11 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 Controller

As its name suggest that it is a Controller that controls the web application, and it works as an intermediary between the Models and the View. A controller takes requests from the user...

3 minutes read.

CodeIgniter Benchmarking Class

The CodeIgniter contains the Benchmarking class that is used to calculate the time difference between two points or the memory usage of the passed statements in the application. By default, the Benchmarking...

7 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.

Download Helper Codeigniter

Download Helper Codeigniter: The download helper function is used to download data from the server to your computer. The data can be any format like text, jpg, mp3, mp4, etc. Loading...

2 minutes read.

CodeIgniter Creating Library

As we know, CodeIgniter has a large collection of library functions that are stored in the system/libraries folder. CodeIgniter also provides some additional functionality in library files. For example, if you want to...

3 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 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.