Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm attempting to import some data from a legacy site into WordPress. First step is terms for taxonomy event_category. Here is my approach:

$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);
}

In my var_dump I'm getting following error:

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
    )
)   

The problem is dkpldump is the database I'm trying to read from, not the database WordPress is installed on (dkpl). So why is it trying to write to dkpldump database and how can I fix it?

share|improve this question
1  
What happens if you pass $link as the second parameter of mysql_query? Would recommend using mysqli too, even if this is just a one time thing. –  Andrew Bartel Jan 31 at 18:27
    
Same thing happens if I pass $link to mysql_query, going to try MYSQLi now if I can –  GhostToast Jan 31 at 18:30
    
Works splendidly with mysqli, and I was forced to improve to a better mysql class. Thanks @AndrewBartel –  GhostToast Jan 31 at 18:55
    
@AndrewBartel if you want to submit such an answer formally, I'll gladly accept it –  GhostToast Jan 31 at 19:21
    
Hey Ghost @Parham's answer is actually the best practices way to do it. Thanks though. –  Andrew Bartel Jan 31 at 21:10

1 Answer 1

up vote 1 down vote accepted

Use a new instance of wpdb to connect and read from the other database:

$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
        )
    );
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.