Welcome Guest, Not a member yet? Register   Sign In
Multiple databases, codeigniter does not re-select the database
#11

[eluser]dignick[/eluser]
I've developed a solution that seems to work ok, however it uses a global variable. I could have used the codeigniter object, but then problems would occur if you started a database in a pre-controller hook for example.
The solution checks if the database is using pconnect, and then cycles through pointers to other database objects that are also using pconnect, checking if the login credentials are equal. It is not safe to just check the connection id as it seems they sometimes differ even for the same connection. If the credentials are the same it sets a property of both objects to TRUE so when executing the sql it knows it needs to switch database.

insert into system/database/DB_driver.php, after line 127 (initialize(), after connection)
Code:
/**** CUSTOM ****/
// multiple dbs with pconnect hack
$this->_select_db_on_execute = FALSE;
// check if pconnect
if($this->pconnect) {
    // check if any dbs with pconnect already exist
    if(isset($GLOBALS['dbs'])) {
        // cycle through all pconnect dbs
        foreach($GLOBALS['dbs'] as &$db) {
            // check if login credentials are equal
            if($db->hostname == $this->hostname &&
                $db->username == $this->username &&
                $db->password == $this->password) {
                
                // they are, so set the property in both dbs
                $this->_select_db_on_execute = TRUE;
                $db->_select_db_on_execute = TRUE;
            }
        }
    }
    // add this db to the array
    $GLOBALS['dbs'][] =& $this;
}
/**** END CUSTOM ****/

That's determined if the database needs selecting before every query, now we need to select it. Insert into system/database/drivers/mysql/mysql_driver.php after line 161 (start of _execute()):

Code:
if($this->_select_db_on_execute) mysql_select_db($this->database, $this->conn_id);

This works for me now if pconnect is true or false.




Theme © iAndrew 2016 - Forum software by © MyBB