0

My code below takes an xml file and inserts it into a database table. However, I would also like to save the full insert query as a backup. Is it possible to write out the query built by wpdb so that I can save it to a file?

function lc_course_database_convert_to_sql( $file ) {
    global $wpdb;
    //$wpdb->show_errors();
    $xml = simplexml_load_file( $file['url'] );
    $tablename   = $wpdb->prefix . 'courses';
    $mydata = new SimpleXmlIterator( $file['url'], 0, true );
    for ( $mydata->rewind();$mydata->valid();$mydata->next() ) {
        //create an array with the column names and corresponding values
        $insertarray = array();
        foreach ( $mydata->current() as $k=>$v ) {
            $insertarray[$k]= (string)$v;
        }
        $wpdb->insert(
            $tablename,
            $insertarray,
            array(
                '%d',
                '%s',
                '%d',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%d',
                '%d',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%d',
                '%d',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                '%d',
                '%s',
                '%s',
                '%d',
                '%s',
                '%s',
                '%d',
                '%d',
                '%s',
                '%s',
                '%d',
                '%d',
                '%d',
                '%d',
                '%d',
                '%d',
                '%d',
                '%d',
                '%d',
                '%d',
                '%d',
                '%d',
                '%d',
                '%d',
            )
        );
    }
}

1 Answer 1

1

Trivial! $wpdb->last_query will hold it. :)

For more extensive log you might want to define SAVEQUERIES constant to true in configuration. Full log then will be available in $wpdb->queries. It's off by default for performance reasons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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