Sometimes we need to connect to multiple databases with our PHP script. Try not to connect to too many different hosts, this can increase considerably the execution time of your script.

First, I create the 2 connection with 2 hosts:

$user1 = "";
$pass1 = "";
$db1 = "";
$host1= "";
$conn1 = mysql_connect($host1, $user1, $pass1);

$user2 = "";
$pass2 = "";
$db2 = "";
$host2 = "";
$conn2 = mysql_connect($host2, $user2, $pass2);

mysql_select_db($db1, $conn1);
mysql_select_db($db2, $conn2);

The second parameters of the mysql_db_select() function will return the handler for the connection to the database. This way I can select the database to run my queries on.

$rez1 = mysql_query("SHOW TABLES FROM `database1`;",$db1);
$rez2 = mysql_query("SHOW TABLES FROM `database2`;",$db2);

2 examples of queries. mysql_fetch_array(), mysql_num_rows() and similar functions don’t need the handler because they work with the queries we ran against the wanted database.

In a similar manner you can connect to even more databases. If you can work with only one database it is recommended to use one. The less, the better.