How to Connect multiple databases using PHP and Mysql

04th, January 2018 By

Today we will learn how to connect to more than one database or multiple database  using the php and mysql.Once i have worked on my project i have faced this situation for connect to two database on the same script .

Simple Database Connection

Normally when we are working we will make the connction using this simple code.

    
<?php // connect to the database server 
$db = mysql_connect("HOST", "USERNAME", "PASSWORD"); 
// select the database to connect 
mysql_select_db("Database_name", $db);
 // query the database 
$query = mysql_query("SELECT * FROM users", $db); 
// close the database connection 
mysql_close($db); ?>

Multiple Database Connection

Now you have to make two database conncetions instead of simple one.For creating two database connction we are connecting  two database using two variable like here $db1 and $db2.These are the variable names we are using for connect that database in query.


<?php 
// connect to the database server 
$db1 = mysql_connect("HOST", "USERNAME", "PASSWORD"); 
// select the database to connect 
mysql_select_db("Database_name", $db1);
 // connect to the second database server 
$db2 = mysql_connect("HOST", "USERNAME", "PASSWORD"); 
// select the database to connect 
mysql_select_db("Database_name", $db2); 
// close the database connections 
mysql_close($db1); 
mysql_close($db2); 
?>
<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>

Query For Multiple Database Connections

Now you will have to run query for database.Just need to add the variable have database connection in mysql_query() function and that specific query work with that database only.Like here query first work with the database first and second query for database second.


// query the first database
$query1 = mysql_query("SELECT * FROM users", $db1);

// query the second database
$query2 = mysql_query("SELECT * FROM images", $db2);

As you will seen like this we will connect to multiple databases.You will add more than two databases using these code.Hope this will help you.

Leave a Reply

Your email address will not be published. Required fields are marked *