How to create custom tables in WordPress using my own plugin?

I am new in WordPress plugin development.
This is my core PHP and HTML code

create-table.html

Read More
  <form method="post" action="function.php">
    <input type="text" name="table_name">
    <input type="submit" name="create">
    </form>

function.php

if(isset($_POST['create'])
{
$table-name=$_POST['table_name'];

//create table query
header("location: add_table_attribute.php");
}

I want to use this same process in my WordPress plugin development. Please any one help me.

Thanks in advance.

Related posts

Leave a Reply

2 comments

  1. Creating Tables with plugin This page shows how to work with tables in plugins. Example on that page includes table creation during installation of plugin. But it can be dynamically used also to create table. See below.

    if(isset($_POST['create'])
    {
    $table_name=$_POST['table_name'];
    

    Note : don’t use – in variable names.

    global $wpdb;
    $sql = "CREATE TABLE $table_name (
      id mediumint(9) NOT NULL AUTO_INCREMENT,
      time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
      name tinytext NOT NULL,
      text text NOT NULL,
      url VARCHAR(55) DEFAULT '' NOT NULL,
      UNIQUE KEY id (id)
    );";
    
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );
    
    //create table query
    header("location: add_table_attribute.php");
    }
    
  2. function create_custom_table()
    {
        global $table_prefix, $wpdb;
        $tblname = 'custom_plugin';
        $wp_track_table = $table_prefix . "$tblname ";
        #Check to see if the table exists already, if not, then create it
        if($wpdb->get_var( "show tables like '$wp_track_table'" ) != $wp_track_table)
        {
            $sql = "CREATE TABLE `wp_custom_plugin` (
                    `id` int(11) NOT NULL AUTO_INCREMENT,
                    `name` varchar(100) NOT NULL,
                    `email` varchar(100) NOT NULL,
                    `phone` varchar(100) NOT NULL,
                    `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                     PRIMARY KEY (`id`)
                    ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ";
            require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
            dbDelta($sql);
        }
    }
    
     register_activation_hook( __FILE__, 'create_custom_table' );