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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器