PHP PDO多个数据库连接选项

PHP PDO多个数据库连接选项

问题描述:

I'm using my localhost to work on my project, but sometimes i need to put the website online to show it for my clients. When i do this i need to change the pdo connection details the webhosting's connection details.

Is there any way in PHP to do it automatically? I mean that i create in various connections, and if PDO cant connect to the first, then tries an another.

$option1 = new PDO('mysql:host=host1;dbname=db1', 'user1', 'pw1');
$option2 = new PDO('mysql:host=host2;dbname=db2', 'user2', 'pw2');
$option3 = new PDO('mysql:host=host3;dbname=db3', 'user3', 'pw3');

I need a script which tries out each of the options, connects to the right database, and returns a simple $db object.

我正在使用我的localhost处理我的项目,但有时我需要将网站放在网上以显示它 为我的客户。 当我这样做时,我需要更改pdo连接详细信息webhosting的连接详细信息。 p>

PHP中有什么方法可以自动执行此操作吗? 我的意思是我在各种连接中创建,如果PDO无法连接到第一个,则尝试另一个。 p>

  $ option1 = new PDO('mysql:host = host1;  dbname = db1','user1','pw1'); 
 $ option2 = new PDO('mysql:host = host2; dbname = db2','user2','pw2'); 
 $ option3 = new PDO  ('mysql:host = host3; dbname = db3','user3','pw3'); 
  code>  pre> 
 
 

我需要一个脚本来尝试每个选项 ,连接到正确的数据库,并返回一个简单的$ db对象。 p> div>

Try

if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' or $_SERVER['REMOTE_ADDR'] == '::1')
{
    # LOCAL
    define('dbhost', 'localhost');
    define('dbuser', 'root');
    define('dbpassword', '');
    define('dbname', 'db');
} else {
    # REMOTE
    define('dbhost', 'example.com');
    define('dbuser', 'remoteUser');
    define('dbpassword', 'remotePass');
    define('dbname', 'remoteDb');
}

$conn = new PDO('mysql:host='.dbhost.';dbname='.dbname.', '.dbuser.', '.dbpassword);