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

报告相同问题?

悬赏问题

  • ¥15 目标计数模型训练过程中的问题
  • ¥100 Acess连接SQL 数据库后 不能用中文筛选
  • ¥15 用友U9Cloud的webapi
  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败