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.

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.