728x90

I just created my first WordPress Plugin. This plugin requires extra table to be created in WordPress database.

The new table will store needed data for my plugin and this table usually created when the plugin is activated.

In that case, I need to check if the table is already in the database or already installed due to previous installations.

HERE’S HOW I CHECK THE DATABASE

Sample code snippets on how to check the database.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
global $wpdb;
$table_name = $wpdb->prefix.'TABLE-NAME-HERE';
if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
     //table not in database. Create new table
     $charset_collate = $wpdb->get_charset_collate();
 
     $sql = "CREATE TABLE $table_name (
          id mediumint(9) NOT NULL AUTO_INCREMENT,
          field_x text NOT NULL,
          field_y text NOT NULL,
          UNIQUE KEY id (id)
     ) $charset_collate;";
     require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
     dbDelta( $sql );
}
else{
}

If you have questions, feel free to contact me or comment below.


+ Recent posts