我必须在我的应用程序中使用多个数据库连接。场景是:
- 我有一个
dm_masterdb
,它保存数据库信息和用户凭据以登录应用 - 登录应用程序后,不再需要此
dm_masterdb
,将从数据库中获取登录用户的数据库信息,并根据其凭据建立连接。现在整个应用程序都在这个新创建的数据库连接上运行,例如userDb
。
现在我一直在做的是:
我创建了以下帮助程序来帮助连接到第二个数据库:
/**
* Aids in connecting to the passed database
* @param string $db_name database name to which the connection is required
* @return object Database object for the connection made
*/
function connectDb($db_name) {
// Get current Codeigniter instance
$CI =& get_instance();
try {
$userDbConfig['hostname'] = $CI->db->hostname;
$userDbConfig['username'] = $CI->db->username;
$userDbConfig['password'] = $CI->db->password;
$userDbConfig['database'] = $db_name;
$userDbConfig['dbdriver'] = "mysqli";
$userDbConfig['dbprefix'] = "";
$userDbConfig['pconnect'] = FALSE;
$userDbConfig['db_debug'] = TRUE;
$userDbConfig['cache_on'] = FALSE;
$userDbConfig['cachedir'] = "";
$userDbConfig['char_set'] = "utf8";
$userDbConfig['dbcollat'] = "utf8_general_ci";
$userDb = $CI->load->database($userDbConfig, true);
return $userDb;
} catch (Exception $e) {
$error = 'The error thrown is: ' . $e->getMessage();
$error .= 'Error thrown while database connection to ' . $db_name;
show_error($error, 500);
log_message( 'error', $error );
}
}
在每个模型的构造函数中都会调用此函数connectDb()
,以在访问数据库之前创建数据库连接。例如,我的模型之一如下:
class Payments extends CI_Model {
private $userDb;
public function __construct()
{
parent::__construct();
$this->userDb = connectDb($this->session->userdata('db_name'));
}
public function fetchChartData($period, $type)
{
//...
$result = $this->userDb->query($query);
return $result->result_array();
}
}
现在的问题是,
- 我的做法正确吗?
- 有什么方法可以提高效率吗?
- 我是否可以断开与
dm_masterdb
的现有数据库连接,并在全局范围内访问与用户数据库的连接,即无需在每个模型的构造函数中创建数据库连接?
最佳答案
在您的database.php中,您有默认配置,例如
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
..............
..............
复制此配置并将default
索引更改为default
之外的其他内容,例如
$db['second_db']['hostname'] = 'localhost';
$db['second_db']['username'] = 'root';
$db['second_db']['password'] = '';
..............
..............
使用第二个数据库
$secondDb = $this->load->database('second_db', TRUE);
那么你将使用 $secondDb->foo()
代替 $this->db->foo()
第二种方法是手动连接数据库,例如
$config['hostname'] = "localhost";
$config['username'] = "myusername";
$config['password'] = "mypassword";
$config['database'] = "mydatabase";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";
$this->load->database($config);
有关更多信息,请参阅此处 http://ellislab.com/codeigniter/user-guide/database/connecting.html
关于php - Codeigniter - 在哪里创建第二个数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20823313/