Connect to another database in WordPress using the wpdb class

In WordPress the $wpdb object can talk to any number of tables, but only within database WordPress is installed. In case you need to connect to another database, you will have to instantiate your own object from the wpdb class with the appropriate connection details:

$mydb = new wpdb( 'username' , 'password' , 'database' , 'localhost' );

 

Once the connection is made you can access the database and its tables as you would in any WordPress database:

$rows = $mydb->get_results("SELECT field1,field2 FROM myTable WHERE field3=1");
foreach ($rows as $row) {
  echo $row->field1;
}

This code can be in plugins, templates, themes and almost anywhere else inside the WordPress code.

Published by

Henrik Damgaard

Hi I’m Henrik and I write this blog based on useful topics I find interesting – mostly covering some of my technical interests : System Center Operations Manager (SCOM), BizTalk, Windows Server, PowerShell, SQL server, Internet Information Services, PHP and .NET I am currently holding a position as System Administrator with focus on Microsoft server products.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.