Connecting to Another MySQL Database With WordPress

Feb 13, 2014 | WordPress

A recent project required that we access data from a separate database, in a custom WordPress page template. The data also needed to be retrieved before the opening <html> tag. By opening another database connection here, WordPress threw a fit, and failed to load the page’s menus. After hours to troubleshooting and searching for answers on countless forums,we finally found a solution…

Original MySQL Database Connection Code:

$connect = mysql_connect('localhost', 'my-user-name', 'my-strong-password') or die("Error, Cannot connect to the database!");
 
mysql_select_db('my-database-name',$connect) or die("Error, Cannot locate the database!");
New Working Code:
$connect = mysql_connect('localhost', 'my-user-name', 'my-strong-password', TRUE) or die("Error, Cannot connect to the database!");
 
mysql_select_db('my-database-name',$connect) or die("Error, Cannot locate the database!");

Note the TRUE parameter is set in the new code. Apparently, if you are trying to open multiple separate MySQL connections with the same username, password, and hostname, you must set this to TRUE to prevent mysql_connect from using WordPress’s existing connection.