Reputation: 2522
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
Upvotes: 0
Views: 270
Reputation: 27295
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.
Upvotes: 1