Tuesday, November 5, 2013

How do you connect to multiple MySQL databases on a single webpage

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




$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 this:
mysql_query('select * from tablename', $dbh1);

and for database 2:
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.

No comments:

Post a Comment