2

I am building a web app with CI 3, I have to use 2 different database connections for certain requirement. I have loaded the configuration to the database.php file and I can of course connect to them using the built in classes.

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

$db['customer'] = array(
    'dsn' => '',
    'hostname' => 'localhost',
    'username' => 'root_1',
    'password' => 'root_1',
    'database' => 'secondary',
    'dbdriver' => 'mysqli'

);

I am using a MY_Model from here. So I extend them as follows..

class Table extends MY_Model
{


    public function __construct()
    {

        parent::__construct();

        $this->_database = $this->load->database('customer', TRUE);
    }

    public function create_table()
    {
    return $this->_database->query("CREATE TABLE MyGuests (
                      id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                      firstname VARCHAR(30) NOT NULL,
                      lastname VARCHAR(30) NOT NULL,
                      email VARCHAR(50),
                      reg_date TIMESTAMP
                    )");

    }

}

But I need to use dbForge to create tables. But only 'default' connection is used with the dbForge class. Codeigniter dbForge documentation doesn't give a way to load different db connections to the dbForge. Anyone know how to tackle the issue in an elegant way?

Fawzan
  • 4,738
  • 8
  • 41
  • 85
  • 1
    Check this [link](http://stackoverflow.com/questions/16500733/codeigniter-dbforge-create-database-and-tables) is this helpful to you?? – Saty Nov 03 '15 at 06:24
  • @Saty I have already went through the link, That doesn't look like an elegant way. specially because I am planning to use migrations and all with the 'secondary' connection. – Fawzan Nov 03 '15 at 06:28
  • You can pass specific parameter via URL and based on URL connect to particular database – Rejoanul Alam Nov 03 '15 at 06:55
  • @RejoanulAlam but Imy problem is on how to use dbForge after selecting the db. – Fawzan Nov 03 '15 at 07:15
  • based on parameter `default` database (in database.php) will be changed and then automatically correct database will be connected. If you need example let me know – Rejoanul Alam Nov 03 '15 at 07:22
  • Actually It is not. But I figured out the right way. I will post it in the answer :D Thanks guys. – Fawzan Nov 03 '15 at 07:42

1 Answers1

1

After little bit research I found the right way to do it.

$this->load->dbForge() can actually take a parameter, If we pass a database object it will use that connection to perform the operation.

In addition, we can pass a second argument and get a separate object as well.

$this->dbForgeSecondary = $this->load->dbforge($this->_database, TRUE);

Easy & Pretty Cool.

Fawzan
  • 4,738
  • 8
  • 41
  • 85