CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
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.
To work with database creation, you need to load the dbforge
library.
$this->load->dbforge();
In:
application/config/autoload.php
Add:
$autoload['libraries'] = array('database', 'dbforge');
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.
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.
You can also drop a database:
$this->dbforge->drop_database('ci_tutorial');