15 Jun, 2004
PHP: working with multiple databases
Posted by: Jennifer In: Lessons learned|Script snippet
I'm in the process of moving a few other blogs over to use WP – one of which makes calls to a seperate database unrelated to WP. This proved to cause a conflict. After many hours of trying to figure out where the specific conflict was – I narrowed it down to my mysql_select_db line. Apparently selecting your database this way – even if you close your mysql connection – and then select a different database later on – it can cause you headaches (and make you stay up later than you had intended to) LOL! =Yawn=
The remedy was specifying the databasename when referencing the table and avoiding using the mysql_select_db line altogether.
So instead of code that looked like this:
$databaseConnection = mysql_connect($databaseServer, $databseUsername, $databasePassword) or
die ('I can't connect to the database.');
mysql_select_db($databaseName,$databaseConnection);
$query = "SELECT * from tablename;";
$result = mysql_query($query);
I changed it to this and it seemed to work:
$databaseConnection = mysql_connect($databaseServer, $databseUsername, $databasePassword) or
die ('I can't connect to the database.');
$query = "SELECT * from " . $databaseName . ".tablename;";
$result = mysql_query($query,$databaseConnection);