Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
843 views
in Technique[技术] by (71.8m points)

mysql - Codeigniter/PHP check if can connect to database

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My question was answered on this thread on Codeigniter forums.

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; 

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...