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?

6
  • 1
    Check this link is this helpful to you?? Commented Nov 3, 2015 at 6: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. Commented Nov 3, 2015 at 6:28
  • You can pass specific parameter via URL and based on URL connect to particular database Commented Nov 3, 2015 at 6:55
  • @RejoanulAlam but Imy problem is on how to use dbForge after selecting the db. Commented Nov 3, 2015 at 7: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 Commented Nov 3, 2015 at 7:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.