Home > Blockchain >  Wordpress insert data when creating table custom plugin
Wordpress insert data when creating table custom plugin

Time:11-05

Hi I am creating a table in wordpress

        $sql = "CREATE TABLE IF NOT EXISTS $wpdb->prefix" . "profil_member(
            id_profil bigint(20)UNSIGNED NOT NULL AUTO_INCREMENT,
            id_member bigint(20) UNSIGNED NOT NULL,
            id_subscription bigint(20) UNSIGNED NOT NULL,
            createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
            updatedAt DATETIME,
            state int DEFAULT 1,
            PRIMARY KEY(id_member,id_subscription),
            FOREIGN KEY (id_profil) REFERENCES $wpdb->prefix" . "profil(id),
            FOREIGN KEY (id_member) REFERENCES $wpdb->prefix" . "member(id)
            ) " . $wpdb->get_charset_collate();

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);

And I want to populate this table when created with date from antoher table

       if (version_compare($version, '1.7') < 0) {
            $this->populate_profil_member();
            update_option('my_plugin_version', '1.7');
        }

Current plugin version is 1.6.

If i load the plugin with the 1.7 update it creates the table but do not insert the data and update the plugin to 1.7

If I load the plugin with the create table and not the insert it creates the table and then If I reload with the update it insert the data and update to 1.7

Is there a solution to just create the table an insert the data at the same time. ?

CodePudding user response:

Follow this example:

function insert_data_into_database() {
    global $wpdb;
    
    $welcome_name = 'Mr. WordPress';
    $welcome_text = 'Congratulations, you just completed the installation!';
    
    $table_name = $wpdb->prefix . 'your-table-name';
    
    $wpdb->insert( 
        $table_name, 
        array( 
            'time' => current_time( 'mysql' ), 
            'name' => $welcome_name, 
            'text' => $welcome_text, 
        ) 
    );
}
  • Related