I want to connect wpdb to another database. How do I create the instance and pass it the database name/username/password?
Thanks
|
|
Yes it's possible. The wpdb object can be used to access any database and query any table. Absolutely no need to be Wordpress related, which is very interesting. The benefit is the ability to use all the wpdb classes and functions like Here's how:
|
|||||||
|
|
Connecting to a second database is easy in WordPress, you simply create a new instance of the WPDB class and use it the same way you would use the standard $wpdb instance we all know and love. Assuming the second database has the same login information as the main WP one you can even use the predefined constants from wp-config.php to avoid hardcoding the login information.
|
|||||
|
|
no one has said this so I thought I'd add an even easier way.. as long as your additional database has the same user/pass details to access it as your wordpress database you can use the database name before the table name like this
|
|||
|
|
|
I can't comment yet, but I wanted to expand on Wadih M.'s answer (which is great). WP's database class is a customized version of Justin Vincent's ezSQL. If you like the interface and you're wanting to do a site that's not WordPress-based, you might want to check it out: http://www.woyano.com/jv/ezsql |
|||
|
|
While these will work, you'll lose the ability to use the "other" custom features such as get_post_custom and wordpress queries. The simple solution is $wpdb->select('database_name'); which changes the database system-wide (a mysql select_db). The database.table method works if you just want to make a simple query, but if you want to access another wordpress blog you can use select. You'll just need to change it back when you're done or your blog may do strange things. |
|||
|
|
|
I was struggling with using I resolved the problem by calling |
||||
|
|
This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.