我想在Codeigniter中使用原始的PHP代码进行备用数据库连接我的原始php代码是:
$db = mysql_connect('remote_server', 'username', 'password'); if(!$db){
$db = mysql_connect('localhost', 'username', 'password') ; }
如果远程mysql服务器由于某种原因而关闭,则连接到备份服务器。
有没有人用CodeIgniter做过这种事情?如果是这样,你会介意分享代码或想法吗?
答案 0 :(得分:3)
更新: 刚刚想出了一个更好的方法。
假设您在database.php中有2个数据库配置,一个是默认配置,另一个是备份 即
$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,一种方法(我会说这是一个相当糟糕的方法,但一种方法),就是弄乱系统文件。在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中进行异常处理的,但基本上你应该处理异常并连接到不同的数据库。
因为我不知道异常处理,所以我创建一个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;
}
}
答案 1 :(得分:0)
看看system/database/drivers/mysql/mysql_driver.php
找到函数function db_connect()
[或function db_pconnect()
取决于您使用的是哪个]
有连接代码:
return @mysql_connect($this->hostname, $this->username, $this->password, TRUE);
更改逻辑以满足您的需要。
顺便说一句,优先使用PDO
驱动程序,默认情况下,codeigniter使用mysql_*
的折旧过程开始。