在另一个数据库上调用MySQL_Query()时,假定WordPress正在使用该数据库

时间:2014-01-31 作者:GhostToast

我正在尝试将一些数据从旧站点导入WordPress。第一步是分类术语event_category. 以下是我的方法:

$link = mysql_connect(
    \'localhost\',
    \'blah\',
    \'blah\'
);

// connect to old database
$dkpl_db = mysql_select_db(\'dkpldump\', $link);

$event_categories = mysql_query(\'SELECT * FROM calendar_cats\');
while($event_category = mysql_fetch_assoc($event_categories)){
    //create term!
    $term = wp_insert_term(
        $event_category[\'categoryId\'],
        \'event_category\',
        array(
            \'slug\' => $event_category[\'categoryName\']
        )
    );
    var_dump($term);
}
在我的var_dump 我收到以下错误:

WP_Error Object
(
    [errors] => Array
    (
        [db_insert_error] => Array
        (
            [0] => Could not insert term into the database
        )
    )
    [error_data] => Array
    (
        [db_insert_error] => Table \'dkpldump.wp_terms\' doesn\\\'t exist
    )
)   
问题是dkpldump 是我试图读取的数据库,而不是WordPress安装的数据库(dkpl). 那它为什么要写信给dkpldump 数据库以及如何修复它?

1 个回复
最合适的回答,由SO网友:Parham 整理而成

使用的新实例wpdb 要连接并读取其他数据库,请执行以下操作:

$mydb = new wpdb(\'blah\',\'blah\',\'dkpldump\',\'localhost\');
$event_categories = $mydb->get_results("SELECT * FROM calendar_cats");
foreach( $event_categories as $event_category ){
    //create term!
    $term = wp_insert_term(
        $event_category->categoryId,
        \'event_category\',
        array(
            \'slug\' => $event_category->categoryName
        )
    );
}

结束