How to create table in wordpress

This blog will guide you through on how to create table in wordpress dynamically.
While writing this blog i am presuming that you know the basics of creating the plug-in.
If you are not clear then you can refer the wordpress hello word plugin tutorial so that you can create the plug-in file inside plug-in folder.

Step 1: copy the content from following block and add it to the plug-in file.
If your plug-in file already had header section then replace with new header written in following code.

Step 2: Save the code inside plug-in file.

Step 3: Activate the plug-in file and see the database you will find table “wp_srv_tutorial” is created.
“wp_” is default prefix for wordpress table.

Step 4: Now deactivate the plug-in via admin section and check database again, table is been removed from the database.

Plugin Name: phptechi plugin to create table dynamically.
Plugin URI:
Description: WordPress plugin tutorial by phptechi
Author: phptechi
Version: 1.0.0
Author URI:
global $wpdb;
$srv_table_prefix = $wpdb->prefix.'srv_';
define('SRV_TABLE_PREFIX', $srv_table_prefix);
register_deactivation_hook(__FILE__ , 'srv_uninstall' );
function srv_install()
    global $wpdb;
    $tableName = SRV_TABLE_PREFIX."tutorial";
    $tblDefination = "CREATE TABLE $tableName (
        name VARCHAR(100) NOT NULL,
        website VARCHAR(100) NOT NULL,
        description text,
	UNIQUE KEY id (id)
    // Populate table with data.
    $wpdb->query("INSERT INTO $tableName(name, website, description) VALUES('First Questions', '','php bloging site')");
function srv_uninstall()
    global $wpdb;
    $tableName = SRV_TABLE_PREFIX."tutorial";
    $tblDefination = "drop table if exists $tableName";
Share this nice post: