更新: より良いアプローチを見つけました。
database.php に 2 つのデータベース構成があるとします。1 つはデフォルトで、もう 1 つはバックアップです。
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'temp_test1';
//.......
$db['backup']=$db['default'];
$db['backup']['hostname'] = 'localhost1';
$db['backup']['username'] = 'root';
$db['backup']['password'] = '';
$db['backup']['database'] = 'temp_test1';
これをdatabase.phpファイルの最後に追加します
//check to see if you can connect
$conn=@mysql_connect($db['default']['hostname'],$db['default']['username'],$db['default']['password']);
if($conn) //check to see if it's connecting, if it is close this connection
{
mysql_close($conn);
}
else{ //if it isnt
$db['default']=$db['backup']; //replace the default credentials with the backup credentials
}
古い投稿: 取るべきアプローチはたくさんあります。
この mysql_ping() を介して特定の接続が開いているかどうかを確認できます。
$conn=mysql_connect(...);
if(mysql_ping($conn)){...};
したがって、この方法を使用して、選択するデータベースを決定できます。
codeigniter の場合、1 つのアプローチ (かなり悪いと言えますが、それでもなおアプローチです) は、システム ファイルをいじることです。DB_Driver のコードのこの部分:
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
if ( ! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
接続を試み、接続が成功したかどうかを確認し、失敗した場合はエラーを返します。
CI で例外処理をどのように行っているかわかりませんが、基本的には例外を処理して別のデータベースに接続する必要があります。
例外処理がわからないので、config フォルダーのホスト名、ユーザー名、パスワード、およびデータベース変数の database_backup.php ファイルを作成するとします。次に、コードをこれに変更します
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
if ( ! $this->conn_id) //oops, first connection failed
{
//no problem, change the credentials of the database to our backup credentials
$ci=&get_instance();
$ci->load->config('database_backup');
$this->username=$ci->config->item('username');
$this->password=$ci->config->item('password');
$this->database=$ci->config->item('database');
$this->hostname=$ci->config->item('hostname');
//try to connect to database once more
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
// No connection resource STILL?nothing we can do now, throw an error
if ( ! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
}