PHP Connect And Run Query To 2 Databases Or More (Multiple Databases)

On Oct 16, 2010 1 comments

Sometimes on your work with PHP you need to connect to 2 or more database. In example, you want to take data on table from database A and process the data. Then you want to insert or update the processed data into database B. Here I will show you how to connect to 2 database and run query from it.

This is the code :

$db1 = mysql_connect($host1, $username1, $password1);
$db2 = mysql_connect($host2, $username2, $password2,

Don't ever forget with the fourth parameter on mysql_connect(the true option), otherwise this cannot work.

mysql_select_db('database1', $db1);
mysql_select_db('database2', $db2);

To make a query on database 1, do :

query1 = mysql_query('select * from tablename', $db1);

and for database 2 :

query2 = mysql_query('select * from tablename', $db2);

To connect to more than 2 database, you just need to add more connection. It may named as $db3, $db4, $db5 and so on.


Shut Risk said...

Thanks bro, that's help me a lot.

Post a Comment