Create a table in the database of WordPress.
A PHP function is used to create a table in the database. While working on WordPress one of the most important thing to know is about how to create a table and how to insert data into the table. The PHP function to create a table in the backend is the following.
register_activation_hook( __FILE__, ‘my_plugin_create_db’ );
function my_plugin_create_db() { global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . ‘db_plugin’; $sql = “CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
username VARCHAR(15) NOT NULL,
email VARCHAR(30) NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;”; require_once( ABSPATH . ‘wp-admin/includes/upgrade.php’ );
dbDelta( $sql );
}
The error will be occurred if the table name you are created is not matching in any condition. So that has to be checked while creating. The code is given in a plugin file that have been created.
The above will create a database in the server. The register_activation_hook is used here to create table when we are activating the plugin .