How to connect multiple database in PHP, MYSQLi & PDO
In this quick tutorial I am going to share you How to connect multiple MySql database in PHP. If you want to connect 2 or more databases on the same instance of MySQL from single PHP script. Suppose you have multiple MySQL databases and you want to display details of those database on single PHP page then You can use following simple methods to make connection with multiple MySQL databases.
First of all I would suggest you to use mysqli and PDO other then mysql , Because after PHP 5.5 version MySQL function deprecated and may not not be available in future.
Multiple database connection using mysqli
$conn1 = new mysqli($hostname, $username1, $password1,$db1); $conn2 = new mysqli($hostname, $username2, $password2,$db2); mysqli_query($conn1,"SELECT * FROM table"); mysqli_query($conn2,"SELECT * FROM table");
Multiple database connection using PDO
$conn1 = new PDO("mysql:host=$hostname;dbname=db1", $username1, $password1); $conn2 = new PDO("mysql:host=$hostname;dbname=db2", $username2, $password2); $conn1->query("SELECT * FROM table"); $conn2->query("SELECT * FROM table");