Advertisement

Google Ad Slot: content-top

CodeIgniter MySQL Create Database


In CodeIgniter, you can create databases either manually using MySQL commands or programmatically using CodeIgniter’s Database Forge class.

The Forge class helps you create, modify, and drop databases/tables easily without writing raw SQL queries.

🔹 Step 1: Load Database Forge Library

To work with database creation, you need to load the dbforge library.

Option 1: Load in Controller

$this->load->dbforge();

Option 2: Autoload (if used frequently)

In:

application/config/autoload.php

Add:

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


🔹 Step 2: Create a Database

Use the following code in your controller to create a database.

class DatabaseController extends CI_Controller {

    public function create_db() {
        // Load Database Forge
        $this->load->dbforge();

        // Create Database
        if ($this->dbforge->create_database('ci_tutorial')) {
            echo "Database created successfully!";
        } else {
            echo "Failed to create database.";
        }
    }
}

👉 Visiting http://your-site/index.php/databasecontroller/create_db

will create a new database named ci_tutorial.

🔹 Step 3: Check if Database Exists

You can also check before creating:

if (!$this->dbforge->create_database('ci_tutorial', TRUE)) {
    echo "Database already exists!";
}

Here, the second parameter TRUE checks existence before creating.

🔹 Step 4: Drop Database (Optional)

You can also drop a database:

$this->dbforge->drop_database('ci_tutorial');


🔹 Best Practices

  • Create databases only during installation/setup, not during normal app runtime.
  • Use phpMyAdmin or MySQL CLI for production environments instead of code-based DB creation.
  • Use migrations for version control instead of creating DB directly.