Dynamic database creation


CodeIgniter's Database library is powerful and I like its ease of use a lot, but for a particular project I need to dynamically create new databases. Getting it to work is no problem. I use mysql_connect and mysql_query, but I wonder if this is the best approach in CodeIgniter? I assume that the Database class cannot be used for this kind of tasks.


Use the database forge class: http://ellislab.com/codeigniter/user-gui...forge.html

That's exactly what I needed. Thanks!

I noticed to issues when reading the user guide on dbforge. When you create a table with dbforge, how does it know to which table it should add the table? Also, you can add a second parameter when creating a table to see if the table already exists, but this option is not available for creating a database. This seems odd or am I overlooking something?


This code solves both your problems.


        $db_name = 'test_db';
        $table_name = 'test_table';

        $dbs = $this->dbutil->list_databases();

        if (in_array($db_name, $dbs)) {
            echo "Database " . $db_name . " is already created.";
        } else {
            if ($this->dbforge->create_database($db_name))
                echo 'Database created!';

        $fields = array(
            'blog_id' => array(
                                     'type' => 'INT',
                                     'constraint' => 5,
                                     'unsigned' => TRUE,
                                     'auto_increment' => TRUE
            'blog_title' => array(
                                     'type' => 'VARCHAR',
                                     'constraint' => '100',
            'blog_author' => array(
                                     'type' =>'VARCHAR',
                                     'constraint' => '100',
                                     'default' => 'King of Town',
            'blog_description' => array(
                                     'type' => 'TEXT',
                                     'null' => TRUE,
        $this->dbforge->add_key('blog_id', TRUE);
        $this->dbforge->create_table($db_name . '.' . $table_name, TRUE);

This is indeed what I was looking for. I didn't know about the dot-notation in the create_table method. That's a handy feature! Thanks a lot.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.