×

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

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.

Retrieve data from Database

Retrieve data from the Database Now we will discuss how we can retrieve data from the database that we have inserted to the employees table of the database in our previous topic “inserted...

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

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

The file helper function is used to perform various tasks with files such as accessing files, writing data to files, deleting files, and more. Loading the File Helper Before using the file helper, you must...

7 minutes read.

CodeIgniter ZIP Encoding Class

ZIP Encoding Class The CodeIgniter provides a Zip encoding class that are used to compress a large file into a Zip archives. And this archives files can be downloaded either to your desktop or...

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

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.

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.

Delete a record from Database CodeIgniter

Delete a record from the Database After inserting, retrieving, and updating table records, we will now learn how we can delete a particular record from a database table. To delete a record, first, we...

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

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

A cookie is a small set of files sent from the web server to the end-user system. In Helpers, the cookie helper file has some predefined functions that are used to the...

4 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 Calendaring Library

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

7 minutes read.