Codeigniter / PHP检查是否可以连接到数据库 [英] Codeigniter/PHP check if can connect to database

查看:114
本文介绍了Codeigniter / PHP检查是否可以连接到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to backup my read replica(i.e., slave) database with my master database but this simple boolean I did failed:

$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);
}

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

After terminating my read replica database I expected the boolean to evaluate to FALSE and the script to then use my master database. Unfortunately, instead I got the following PHP error:

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

所有我想要的是连接返回true

All i want is for the connection to return true or false, does anyone know how to do this in Codeigniter?

推荐答案

我的问题回答了此代码在Codeigniter论坛

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

The key is to not autoinitialize the database:

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

为了抑制错误,您可以设置

To suppress errors it you can set this

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


$ b <

Then in your code that checks the db state, check TRUE/FALSE of the initialize() function:

$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

Here is my entire config file for future reference: https://gist.github.com/3749863.

这篇关于Codeigniter / PHP检查是否可以连接到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆