Connecting to Multiple MySQL Databases with PHP

I ran into a case where I needed to connect to two seperate databases within the same script, and I didn’t know how to do it without closing one connection, and opening another.  With a little time and effort, I figured it out, and it’s quite simple.

Here is the PHP code to connect to a database:

$db1 = mysql_connect('localhost', 'db-user', 'db-password');

What this does is store the connection link in the variable $db1. Then you choose which database to you with the second line. With this code, you can then run mysql commands just like this:

$query = mysql_query("SELECT * FROM yourtable;);

Now, in the case where you need to do some work with a different database, you don’t want to be closing and opening connections all the time. So, when you make your database connections, it’s very easy. This is what the code looks like with 3 database connections open (of course, you’d have to change all the variables for each different database):

$db1 = mysql_connect('localhost', 'db-user', 'db-password');
mysql_select_db('db-name', $db1);
$db2 = mysql_connect('localhost', 'db-user', 'db-password');
mysql_select_db('db-name', $db2);
$db3 = mysql_connect('localhost', 'db-user', 'db-password');
mysql_select_db('db-name', $db3);

You will probably want to rename the $db1 varables with something more suggestive of which database you are using just for clarity. Now, to use these different database connections, all you have to do is add that connection link to the end of your query like this:

$query1 = mysql_query("SELECT * FROM yourtable", $db1);
$query2 = mysql_query("SELECT * FROM differenttable ORDER BY column DESC", $db2);
$query3 = mysql_query("SELECT somevalue FROM table WHERE id = 20", $db3);

And that’s all there is to it!

This entry was posted in MySQL, PHP. Bookmark the permalink.

Comments are closed.