Home > other >  how to make multiple connection to database using php and mysql
how to make multiple connection to database using php and mysql

Time:02-03

I have an associative array contain multiple database configuration and I want to make all connection to database in this array

$dbconfig = array(
    'servername' => array('localhost','localhost'),
    'username' => array('root1','root2'),
    'password' => array('p1','p2'),
    'db' => array('db1','db2'),
);
 $conn = mysqli_connect($dbconfig['servername'], $dbconfig['username'], $dbconfig['password'], $dbconfig['db']);

CodePudding user response:

You should transpose your array structure to this:

<?php
$dbconfig = array(
    array(
        'servername' => 'localhost',
        'username' => 'root1',
        'password' => 'p1',
        'db' => 'db1'
    ),
    array(
        'servername' => 'localhost',
        'username' => 'root2',
        'password' => 'p2',
        'db' => 'db2'
    )
);

Because this allows you to more easily iterate through the array:

for($i = 0; $i < sizeof($dbconfig); $i  ) {
    $conn[$i] = mysqli_connect($dbconfig[$i]['servername'], $dbconfig[$i]['username'], $dbconfig[$i]['password'], $dbconfig[$i]['db']);
}
  •  Tags:  
  • php
  • Related