×

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

Language Class The CodeIgniter’s language class contains the various functionality that is used to access the language-specific files and text line for the purposes of internationalization. This class provides you suitability to add or...

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

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

Directory Helper Codeigniter

Directory Helper CodeIgniter: provides a directory helper function that works with the directory. It shows the structure of the file, hidden file in the folder, and the folder in...

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

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 Security Helper

A Security helper file contains some predefined functions that are used to protect application from unauthorized access. Loading the Helper The following syntax is used to load the security helper in the CodeIgniter application. Syntax $this-> load->...

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

The Routes are used to handle URL requests on the browser. It matches the URL request to the predefined routes in CodeIgniter. Therefore, a file must be predefined as a routes.php file to...

6 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 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 Array Helper

The Array Helper contains some predefined functions that are used to perform the various operation with array. Load Array helper It is used to load the helper class. We can pass the helper function in the...

6 minutes read.

Structure of Codeigniter

The File structure of CodeIgniter is divided into three parts: ApplicationSystemuser_guide Application -: As the name represents Application, which contains all the main parts of the project like a controller, libraries, view, models, and others....

3 minutes read.

CodeIgniter String Helper

The string helper file contains functions that allows separate operations with strings in CodeIgniter. Loading the String Helper Before using the string helper in the CodeIgniter application, you must load it in the controller...

7 minutes read.

Versions of CodeIgniter

CodeIgniter v3.1.11 (This is the current version which we will used in this tutorial)CodeIgniter v3.1.10CodeIgniter v3.1.9CodeIgniter v3.1.8CodeIgniter v3.1.7CodeIgniter v3.1.6CodeIgniter v3.1.5CodeIgniter v3.1.4CodeIgniter v3.1.3CodeIgniter v3.1.2CodeIgniter v3.1.1CodeIgniter v3.1.0CodeIgniter v3.0.6CodeIgniter...

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

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.

CodeIgniter Shopping Cart Class

It contains the various function that enables the user to add or update, display, and delete data item from the shopping carts while browsing the site. The items added in the cart...

10 minutes read.