dongmi0760 2017-02-17 21:06
浏览 101

在PDO中创建多个数据库连接

if I have an array of server ip addresses:

 $servers = array('1.2.3.4','4.5.6.7','7.8.9.10');

how can i loop through them and connect to db, get data from each server, then close?

 foreach ($servers as $v){
    $bdb = new PDO('mysql:host='.$v.';dbname=someDB','user','pass');
    $sel = "SELECT data from table";
    $stmt = $bdb->query($sel);
    while($r = $stmt->fetch()){
          $result[$v]['data'] = $r['data'];
    }
 }

My desired result would be:

    print_r($result);

 array
 (
     [1.2.3.4] => Array
                 (
                   [data] => 'someData'
                 )
     [2.3.4.5] => Array
                 (
                   [data] => 'someOtherData'
                 )
     [7.8.9.10] => Array
                 (
                   [data] => 'someOtherOtherData'
                 )
  )

currently the above code only produces results from the first value in servers array.

I have tried setting $bdb=NULL and unset($bdb) with no luck

  • 写回答

1条回答 默认 最新

  • drqrdkfue521903877 2017-02-17 21:15
    关注

    I think you have to close the connection after every iteration. Otherwise you have to build an array with connections and don't same them everytime in the same variable.

    foreach ($servers as $v){
        $bdb = new PDO('mysql:host='.$v.';dbname=someDB','user','pass');
        $sel = "SELECT data from table";
        $stmt = $bdb->query($sel);
        while($r = $stmt->fetch()){
              $result[$v]['data'] = $r['data'];
        }
        $bdb = null;
    }
    

    It should work if you close the connection in that way set your variable to null and delete the connection. Then it should be possible to make a new one in the next iteration.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog