Using WPDB to connect to an external database

Looking to use WPDB to connect to an external database in WordPress? You just need to create a new WPDB connection to link to an external database.

Connecting to a new database using WPDB

In order to connect to an external database in WordPress, you should use the following example below and change the database fields accordingly.

$mydb = new wpdb( 'database_username', 'database_password', 'database_name', 'database_host' );

$rows = $mydb->get_results( 'SELECT field_name FROM table_name' );

foreach ( $rows as $row ) :
     echo $row->field_name;
endforeach;