Search code examples
phpclasscodeigniter-3forge

Codeigniter 3 - How to use Forge Class to create a database schema?


I'm using CodeIgniter 3.1.0 to develop an app. In order to improve installation, I've written an Install_Controller, and an Install_Model.

I want to use Database Forge class to manage the database schema, but it's not very clear in user guide and nothing on Google helps.

I need to use $this->dbforge->create_database, because the user knows nothing about database, so all he will do is MySQL "Next, next, install" and then run a batch file that run PHP as web server, so from Chrome he can use URL to install the app.

User guide says: In order to initialize the Forge class, your database driver must already be running, since the forge class relies on it.

So I have setup the config/database.php with user, pwd, dbname and so on... Even because I need it to use in app.

When I try to load the URL to install the app, give me the error: Message: mysqli::real_connect(): (HY000/1049): Unknown database 'test'

So, how can I use Forge Class to create database schema, if I need to have it first?

Some code...

$db['default'] = array(
    'dsn' => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'database' => 'test',
    'dbdriver' => 'mysqli'
);

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

class Install extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->load->model('install_model');
        $this->install_model->createDabase();
    }
}

class Install_model extends CI_Model {
    function __construct() {
        parent::__construct();
    }

    function createDabase() {
        $this->load->dbforge();

        if ($this->dbforge->create_database('test'))
            echo 'Database created!';
        else
            echo 'Database error!';
    }
}

Solution

  • After try and get a lot of opinions, the only way is as I commented:

    1. Remove database from autoloader;
    2. Use multiple databases, the default one is the same, but create a second one having empty database name;
    3. Use the second database with Forge Class, instead of the default, only for create database and tables;
    4. Change manually for the the default database and use it after that.