gpt4 book ai didi

php - Codeigniter/PHP 检查是否可以连接到数据库

转载 作者:可可西里 更新时间:2023-11-01 06:54:00 24 4
gpt4 key购买 nike

我想用我的主数据库备份我的只读副本(即从属)数据库,但是我做的这个简单的 bool 值失败了:

$config['hostname'] = "myReadReplicaDatabase.com";
//...$config['other_stuff']; other config stuff...
$db_obj=$CI->load->database($config, TRUE);

if(!$db_obj){
$config['hostname'] = "myMasterDatabase.com";
$db_obj=$CI->load->database($config, TRUE);
}

终止我的只读副本数据库后,我希望 bool 值的计算结果为 FALSE,然后脚本会使用我的主数据库。不幸的是,我得到了以下 PHP 错误:

Unable to connect to your database server using the provided settings.
Filename: core/Loader.php

我只想让连接返回 true 或 false,有人知道如何在 Codeigniter 中执行此操作吗?

最佳答案

我的问题在 this thread on Codeigniter forums 上得到了回答.

关键是自动初始化数据库:

$db['xxx']['autoinit'] = FALSE; 

要抑制错误,你可以设置它

$db['xxx']['db_debug'] = FALSE; 

然后在检查数据库状态的代码中,检查 initialize() 函数的 TRUE/FALSE:

$db_obj = $this->database->load('xxx',TRUE);
$connected = $db_obj->initialize();
if (!$connected) {
$db_obj = $this->database->load('yyy',TRUE);
}

这是我的整个配置文件以供将来引用:https://gist.github.com/3749863 .

关于php - Codeigniter/PHP 检查是否可以连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12483861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com