doubi8512 2015-08-03 10:55 采纳率: 0%
浏览 153
已采纳

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.

  • 写回答

1条回答 默认 最新

  • duanlu0075 2015-08-03 11:06
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?