I need to connect to another database, using another user in an extension. How do I go about doing that? Thanks
I currently use this, can I create another connection?
$this->EE =& get_instance();
$query = $this->EE->db->get('other_database.characters');Moved to Development and Programming by Moderator
To get this working, first you need to go to the system/expressionengine/config/database.php file (depending on your setup it might be somewhere else) and add the other database connection information to it. Example:
//standard databases connection information
$db['expressionengine']['hostname'] = "localhost";
$db['expressionengine']['username'] = "db_username";
$db['expressionengine']['password'] = "db_password";
$db['expressionengine']['database'] = "db_name";
$db['expressionengine']['dbdriver'] = "mysql";
$db['expressionengine']['dbprefix'] = "exp_";
$db['expressionengine']['pconnect'] = FALSE;
$db['expressionengine']['swap_pre'] = "exp_";
$db['expressionengine']['db_debug'] = TRUE;
$db['expressionengine']['cache_on'] = FALSE;
$db['expressionengine']['autoinit'] = FALSE;
$db['expressionengine']['char_set'] = "utf8";
$db['expressionengine']['dbcollat'] = "utf8_general_ci";
$db['expressionengine']['cachedir'] = "/expressionengine/cache/db_cache/";
//notice the array index of secondary, we will use this later...
$db['secondary']['hostname'] = "localhost";
$db['secondary']['username'] = "db_username";
$db['secondary']['password'] = "db_password";
$db['secondary']['database'] = "db_name";
$db['secondary']['dbdriver'] = "mysql";
$db['secondary']['dbprefix'] = ""; // <---- Make sure this is empty or set to another prefix if you are using one
$db['secondary']['pconnect'] = FALSE;
$db['secondary']['swap_pre'] = ""; // <---- Make sure this is empty or set to another prefix if you are using one
$db['secondary']['db_debug'] = TRUE;
$db['secondary']['cache_on'] = FALSE;
$db['secondary']['autoinit'] = FALSE;
$db['secondary']['char_set'] = "utf8";
$db['secondary']['dbcollat'] = "utf8_general_ci";
$db['secondary']['cachedir'] = "/expressionengine/cache/db_cache/";Now lets assume we are inside of a plugin and we want to use this secondary database connection:
$this->EE = get_instance();
//get entries form main EE db
$entries = $this->EE->db->from('channel_titles')->get();
/*
Things to note:
1. We are using the secondary index we specified in the database.php file
2. And we are passing TRUE as the second parameter
3. Lastly we are assigning the new database connection to the variable $secondary_db
*/
$secondary_db = $this->EE->load->database('secondary', TRUE);
//get people from the secondary db
$people = $secondary_db->from('people')->get();
//... other cool code ....Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.