Tell PHP To Connect To Two Different MySQL Database's

1 post Page 1 of 1
Contributors
User avatar
mikethedj4
VIP - Site Partner
VIP - Site Partner
Posts: 2592
Joined: Thu Mar 25, 2010 4:36 am

I don't know if anyone else was having this problem or not, but I search on StackOverflow which is where I ask most of my web development questions, and I came across this answer.
You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for the '$new_link' (fourth) parameter, otherwise the same connection is reused.

so then you have
Code: Select all
$dbh1 = mysql_connect($hostname, $username, $password); 
$dbh2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
Then to query database 1, do
Code: Select all
mysql_query('select * from tablename', $dbh1);
and for database 2
Code: Select all
mysql_query('select * from tablename', $dbh2);
Alternatively, if the mysql user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same MySQL connection) you could:
  • Keep one connection open and keep calling mysql_select_db() to swap between. I don't think this is a clean solution and you will easily get cases where you query the wrong db etc.
  • Use queries where you specify the database name (e.g. SELECT * FROM database2.tablename), but this is again likely to be a pain to implement.
I thought I'd share this as this saved me hours of work, and I'm sure it will to you all as well.
1 post Page 1 of 1
Return to “Help & Support”