CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
After creating a database in CodeIgniter, the next step is to create tables.
You can create tables either by writing raw SQL queries or using CodeIgniter’s Database Forge Class.
The Forge Class is useful for creating and modifying tables programmatically in your app.
Just like with database creation, load the dbforge
library.
$this->load->dbforge();
Or add it to autoload.php:
$autoload['libraries'] = array('database', 'dbforge');
Each table is created by defining its fields as an array.
users
Tableclass TableController extends CI_Controller { public function create_table() { // Load Database Forge $this->load->dbforge(); // Define fields $fields = array( 'id' => array( 'type' => 'INT', 'constraint' => 11, 'unsigned' => TRUE, 'auto_increment' => TRUE ), 'name' => array( 'type' => 'VARCHAR', 'constraint' => '100', ), 'email' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'unique' => TRUE, ), 'created_at' => array( 'type' => 'DATETIME', 'null' => TRUE, ) ); // Add fields $this->dbforge->add_field($fields); // Add primary key $this->dbforge->add_key('id', TRUE); // Create table if ($this->dbforge->create_table('users')) { echo "Users table created successfully!"; } else { echo "Failed to create table."; } } }
👉 Visit:
http://your-site/index.php/tablecontroller/create_table
and it will create a users table.
If you want to remove a table:
$this->dbforge->drop_table('users');
You can also add/remove fields.
✅ Add new column:
$fields = array( 'phone' => array( 'type' => 'VARCHAR', 'constraint' => '15', 'null' => TRUE, ) ); $this->dbforge->add_column('users', $fields);
✅ Drop column:
$this->dbforge->drop_column('users', 'phone');
user
, post
, order
).