Create Database dalam Codeigniter Menggunakan Migration

6:28 PTG 0 Comments A+ a-

Create ci_tuto dalam phpmyadmin



create folder migrations dan file 001_create_posts.php didalam folder application

taip di file 001_create_posts.php, migra kemudian tekan ctrl+space dalam sublime text, akan keluar


setting di database




Taip migra kemudian ctrl+space dalam 001_create_posts.php

Didalam function up difile 001_create_posts.php, letak:


defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Create_posts extends CI_Migration {

	public function __construct()
	{
		$this->load->dbforge();
		$this->load->database();
	}

	public function up() {
		$this->dbforge->add_field(
			array(
				'id'=>array(
					'type'=> 'INT',
					'constraint' =>5,
					'unsigned' =>TRUE,
					'auto_increment' =>TRUE
				),

				'title'=>array(
					'type'=> 'VARCHAR',
					'constraint' => 200
				),
				'body'=>array(
					'type'=> 'TEXT',
					'null' =>TRUE
				),
				'created_at'=>array(
					'type'=> 'timestamp',
				),
			)
		);
		$this->dbforge->add_key('id',TRUE);
		$this->dbforge->create_table('posts');
	}

	public function down() {
		$this->dbforge->drop_table('posts');
				
	}

}
Kemudian:

Pergi ke application->config->migration.php
$config['migration_enabled'] = TRUE;

$config['migration_type'] = 'timestamp'; tukar kepada:
$config['migration_type'] = 'sequential';

$config['migration_version'] = 0; tukar kepada:
$config['migration_version'] = 1;



Pergi ke application->config->autoload.php
$autoload['libraries'] = array();  tukar kepada;
$autoload['libraries'] = array('database');


FULL Coding untuk 001_create_post.php:
full coding untuk migrate.php
taip controller kemudian tekan ctrl+space untuk auto script snippet. Tukar nama class kepada Migrate dan letak code seperti dibawah:


defined('BASEPATH') OR exit('No direct script access allowed');

class Migrate extends CI_Controller {

	public function __construct()
	{
		parent::__construct();


	}



	public function index()
	{
		$this->load->library('migration');

		if($this->migration->current()===FALSE)
		{
			show_error($this->migration->error_string());

		}
		else{
			echo "Migration executed !!";
		}
		
	}

}






Run di browser:
Di database: