dbDelta with the character ;

To manage database plugin update, I changed my code using dbDelta.

old code

myfunction(){
   ...
   $query_string = "INSERT INTO {$table_name} {$str_column_names} VALUES {$str_values}";

   $is_data_inserted = $wpdb-query( $query_string );

   if( !$is_data_inserted ){
       $message_error = sprintf( "impossible to insert the data %s for the table %s!",
       serialize( $data_item_attrs ),
            $table_name
        );
        $wpdb-show_errors();
        wp_error_log( $message_error, "Insert Data Error" );
        return false;
    }
    return true;
}

new code

myfunction(){
   ...
   $query_string = "INSERT INTO {$table_name} {$str_column_names} VALUES {$str_values}";
   dbDelta( $query_string ); 
}

My problem is using dbDelta disturbs inserts containing the character ";". It´s because in dbDelta, there is ";" as delimiter.

How can I fix this ?

Topic dbdelta Wordpress

Category Web


That happens for this reason :

The function dbDelta can receive as first parameter ($queries) an array or a string. If $queries is a string, dbDelta will make an array with ";" as delimiter.

inside dbDelta

if ( !is_array($queries) ) {
    $queries = explode( ';', $queries );
    $queries = array_filter( $queries );
}

So the solution is to make an array of queries instead of a string as a first parameter like this:

myFunction(){
    ...
    $query_string = array(
        0 => "INSERT INTO {$table_name} {$str_column_names} VALUES {$str_values}"
    );
    dbDelta( $query_string ); 
}

The answer was found here.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.