Advertisement

Google Ad Slot: content-top

CodeIgniter MySQL Create Table


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.

🔹 Step 1: Load Database Forge

Just like with database creation, load the dbforge library.

$this->load->dbforge();

Or add it to autoload.php:

$autoload['libraries'] = array('database', 'dbforge');


🔹 Step 2: Define Table Fields

Each table is created by defining its fields as an array.

Example: Create users Table

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

🔹 Step 3: Drop Table (Optional)

If you want to remove a table:

$this->dbforge->drop_table('users');


🔹 Step 4: Modify Table (Optional)

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');


🔹 Best Practices

  • Use Migrations in CodeIgniter for team projects to track DB changes.
  • Keep table names lowercase & singular (user, post, order).
  • Always define a primary key.