How to Connect Multiple Databases using PDO in PHP

In this article, we are going to Connect Multiple Databases using PDO in PHP. This is a short article on how to connect multiple databases in the same query using the PDO in MySQL. First, we are going to recall the older mysql_extension on how to create a query connection in multiple databases to MySQL.

Query of the older mysql_extension in multiple databases.

  1. <?php
  2.  
  3. //Select database one. - Query database one.
  4. mysql_select_db('database_one',mysql_connect('localhost','root',''))or die(mysql_error());
  5.  
  6. //Select database two. - Query database two.
  7. mysql_select_db('database_two',mysql_connect('localhost','root',''))or die(mysql_error());
  8.  
  9. ?>
  10.  
  11. <!---OR-->
  12.  
  13. <?php
  14.  
  15. //Connect to MySQL.
  16. $database = mysql_connect('localhost', 'root', '')or die(mysql_error());
  17.  
  18. //Select database one. - Query database one.
  19. mysql_select_db('database_one', $database)or die(mysql_error());
  20.  
  21. //Select database two. - Query database two.
  22. mysql_select_db('database_two', $database)or die(mysql_error());
  23.  
  24. ?>
As you can see in the source code above, it's all the same MySQL connection that we are used in all through query. And, that's the query for the old mysql_extension in PHP. However, in the PDO query, there's a little bit different when we are going to construct the multiple databases connection in MySQL.

Query using PDO in MySQL.

  1. <?php
  2.  
  3. //Connect to MySQL - database one.
  4. $database_One = new PDO('mysql:host=localhost;dbname=database_one', 'root', '');
  5.  
  6. //Connect to MySQL - database two.
  7. $database_Two = new PDO('mysql:host=localhost;dbname=database_two', 'root', '');
  8.  
  9. ?>
This is the PDO query for the multiple databases connection in the MySQL. Hope that this article will help you a lot. Share us your thoughts and comments below. Thank you so much for dropping by and reading this tutorial post. For more updates, don’t hesitate and feel free to visit this website more often and please share this with your friends or email me at [email protected]. Practice Coding. Thank you very much.

Add new comment