1

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 ?

  • please check this code : myfunction(){ global $wpdb; $query_string = "INSERT INTO {$table_name} {$str_column_names} VALUES {$str_values}"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $query_string ); } – vikrant zilpe Jan 2 '19 at 13:43
  • Why are you trying to use dbDelta for inserting data? That's not what it's for. It's intended for creating and modifying tabes. To insert data use $wdb->insert(). – Jacob Peattie Jan 2 '19 at 13:56
  • yes jacob is always right – vikrant zilpe Jan 2 '19 at 13:58
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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