我想连接另一个wp db&;然后从新连接的数据库中提取记录,然后关闭该数据库。
我遵循How can I connect to another WP database and use WP_Query? 但在连接到新数据库后,如果我打印$wpdb
它不显示新的db表。代码如下:
global $wpdb;
$wpdb_backup = $wpdb;
$wpdb = new wpdb( NEWS_DB_USER, NEWS_DB_PASSWORD, NEWS_DB_NAME, NEWS_DB_HOST );
# Do your stuff here...
var_debug($wpdb);
# then when done...
$wpdb = $wpdb_backup;
下面是我在wp config中定义的变量。php
NEWS_DB_USER, NEWS_DB_PASSWORD, NEWS_DB_NAME, NEWS_DB_HOST
输出为:
wpdb Object
(
[show_errors] =>
[suppress_errors] =>
[last_error] =>
[num_queries] => 0
[num_rows] => 0
[rows_affected] => 0
[insert_id] => 0
[last_query] =>
[last_result] =>
[result:protected] =>
[col_info:protected] =>
[queries] =>
[prefix] =>
[ready] => 1
[blogid] => 0
[siteid] => 0
[tables] => Array
(
[0] => posts
[1] => comments
[2] => links
[3] => options
[4] => postmeta
[5] => terms
[6] => term_taxonomy
[7] => term_relationships
[8] => commentmeta
)
[old_tables] => Array
(
[0] => categories
[1] => post2cat
[2] => link2cat
)
[global_tables] => Array
(
[0] => users
[1] => usermeta
)
[ms_global_tables] => Array
(
[0] => blogs
[1] => signups
[2] => site
[3] => sitemeta
[4] => sitecategories
[5] => registration_log
[6] => blog_versions
)
[comments] =>
[commentmeta] =>
[links] =>
[options] =>
[postmeta] =>
[posts] =>
[terms] =>
[term_relationships] =>
[term_taxonomy] =>
[usermeta] =>
[users] =>
[blogs] =>
[blog_versions] =>
[registration_log] =>
[signups] =>
[site] =>
[sitecategories] =>
[sitemeta] =>
[field_types] => Array
(
)
[charset] => utf8
[collate] =>
[real_escape] => 1
[dbuser:protected] => root
[dbpassword:protected] =>
[dbname:protected] => africac_web
[dbhost:protected] => localhost
[dbh:protected] => Resource id #320
[func_call] =>
[is_mysql] => 1
)
最合适的回答,由SO网友:user1777018 整理而成
这是我所做的,根据你的需要稍作改动。可能对你有帮助。:)
function fetch_news()
{
global $wpdb;
$wpdb_backup = $wpdb; // backup existing instance
$wpdb = new wpdb( NEWS_DB_USER, NEWS_DB_PASSWORD, NEWS_DB_NAME, NEWS_DB_HOST ); // create new db instance
wp_set_wpdb_vars(); // add variable
$news_sql = $wpdb->get_results("SELECT * FROM rss_news"); // your query to external db table using $wpdb object
or
$news_sql = mysql_query("SELECT * FROM rss_news"); // your query to external db table
$wpdb = $wpdb_backup; // restore old instance
return $news_sql;
}