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: http://www.phptechi.com
Description: WordPress plugin tutorial by phptechi
Author: phptechi
Version: 1.0.0
Author URI: http://www.phptechi.com
*/
global $wpdb;
$srv_table_prefix = $wpdb->prefix.'srv_';
define('SRV_TABLE_PREFIX', $srv_table_prefix);
register_activation_hook(__FILE__,'srv_install');
register_deactivation_hook(__FILE__ , 'srv_uninstall' );
function srv_install()
{
    global $wpdb;
    $tableName = SRV_TABLE_PREFIX."tutorial";
    $tblDefination = "CREATE TABLE $tableName (
        id INT(11) NOT NULL AUTO_INCREMENT,
        name VARCHAR(100) NOT NULL,
        website VARCHAR(100) NOT NULL,
        description text,
	UNIQUE KEY id (id)
    );";
    $wpdb->query($tblDefination);
    // Populate table with data.
    $wpdb->query("INSERT INTO $tableName(name, website, description) VALUES('First Questions', 'phptechi.com','php bloging site')");
}
function srv_uninstall()
{
    global $wpdb;
    $tableName = SRV_TABLE_PREFIX."tutorial";
    $tblDefination = "drop table if exists $tableName";
    $wpdb->query($tblDefination);
}
Share this nice post: