How to setup and run Codeigniter Migration

Database migration is one of the best features that you get in any PHP framework. Database migration in the framework is just like a version control of your database tables. And another feature of migration is that you don’t have to send or put separate database file to other developers.

Codeigniter also comes with builtin migration feature and we are going to learn how to steup and run database migration

First let’s have a fresh copy of codeigniter from its site. You are unfamiliar with codigniter installation, no worries you can check my post how to install codeigniter in XAMPP.

Enable Migration:

By default migration is disabled in codeigniter. You have to enable it by going to config/migration.php and $config['migration_enabled'] to TRUE

Create Migration Folder:

Next thing is to create a migrations folder in the application folder. Remember name of the folder must be in plural no singular.

Ways to create Migration File(s):

There are 2 ways to create a migration file. Means name of the file should be in following 2 ways.

  1. Sequential: Migration file name should start with 001. Each number should start with 3 digits and there must not be any gaps in the sequence.
  2. Timestamp: Each migration is numbered using the timestamp and format must be YYYYMMDDHHIISS (e.g. 20181208100537)

By default, timestamp is set to migration type. But you can change this by going to config/migration.php file and set $config['migration_type'] value from timestamp to sequential

In this tutorial, I will be using a sequential type.

Create Migration File:

Migration file must extend CI_Migration class and class will have 2 functions. One is up() and second is down(). Up function will have table creation code and down function will get drop table code. $this->dbforge is a database manage class which will take care of database. You can visit Database Forge Class for further digging.

Now let’s create a migration for users table. I am creating a file in application/migrations folder as 001_Users.php

After creating 001_Users.php goto config/migration.php and set $config['migration_version'] value to 1 and $config['migration_auto_latest'] to TRUE

Run Migrations:

Now create a migration controller in controllers folder. I will create Migration.php and write below code.

Before running migration make sure you have already setup your database in config/database.php file. Now go to browser and type localhost/your_project/migration/index. If all goes well, migrations and users table will create in database.

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

PAGE TOP
error

Enjoy this blog? Please spread the word :)

RSS
Follow by Email