How to access another Database in WordPress

wpdb is the class that helps you to manipulate the database in WordPress. But you can not access it directly, you have to use the global object $wpdb to manipulate the database. The Database configuration is stored in wp-config.php during installation process. Highlighted like this

/** The name of the database for WordPress */
define('DB_NAME', 'database_name_here');

/** MySQL database username */
define('DB_USER', 'username_here');

/** MySQL database password */
define('DB_PASSWORD', 'password_here');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

 

How to add another Database?

$wpdb object is reserved with the default Database configuration, So if we required to access another Database in WordPress then simply add the Database information in the wpdb class.

$DB_USER = "";
$DB_PASSWORD = "";
$DB_NAME = "";
$DB_HOST = "";

$newdb = new wpdb($DB_USER, $DB_PASSWORD, $DB_NAME, $DB_HOST);

 

With this you have successfully established a new Database connection and the same WordPress query works with your newly created Object. You can on errors echoing with $wpdb->show_errors() or if you want to print the error(If any) by the most recent query with $wpdb->print_error().

Posted by Jogesh Sharma

Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog.