Last week, I had an opportunity to revamp one of my other blogs, and I updated it to a full Wordpress site with all the bells and whistles. One of the things I wanted to do was include a separate database for my published works, so I could list off what had been published recently and list off upcoming stories and events. Since these were two different MySQL databases, it seemed a no-brainer to just create a second connection to MySQL for the second database and make straight-up calls into it for my sidebar.

That was a failure. Using a second database broke my connection to the first. The sidebar rendered just fine, but the footer then failed to render at all. The MySQL objects created upon connection retain some unique, singleton state, and refer to that state whenever you try to use that connection.

There is a way to isolate the two connections, however. The break happens when you force a query to search for the connection, and by telling the query which connection to use, you avoid the break in communications with the first established connection.

$sdb = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, true);
$res  = mysql_db_query("pw_stories", "select title, source, blurb, sortorder from " +
                       "serials order by sortorder", $sdb);

You see that $sdb variable at the end of the query? That's all it takes. Append that to every query and your established $wpdb connection will not be destroyed even as you access the $sdb database.

Always remember when you're done with a result to clear it:

mysql_free_result($res);

And when you're done with the second connection to close it:

mysql_close($sdb);

That's all there is to it. Now you can include all manner of customized database-driven stuff in your Wordpress without fear.