Search code examples
databasewordpresspsd

Make two or more than one tables on wordpress plugin activation


I was making a plugin completely from scratch recently I tried to make a table on plugin activation and I got successful in the same, but now I want to make more than one table on plugin activate, but I am not getting the expected result.

It making only one table out of two, here is my code below.

// Registering plugin

register_activation_hook(__FILE__,'myplugin_activate'); 

function myplugin_activate() 

{

                global $wpdb;
                $table_name1 = $wpdb->prefix . "myentries";
                $table_name2 = $wpdb->prefix . "myemail";

                //installed_ver = get_option('my-voting-version');

                if( $wpdb->get_var("show tables like '$table_name1' ") != $table_name1)  
                {

                    $sql = "CREATE TABLE IF NOT EXISTS `" . str_replace('`', '', $table_name1) . "`(
                    id mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
                    name varchar(50) NOT NULL,
                    sub longtext NOT NULL,
                    message longtext NOT NULL,                   
                    );";
                    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
                    dbDelta($sql);
                }   
               if( $wpdb->get_var("show tables like '$table_name2' ") != $table_name2 )      
                {    
                    $sql = "CREATE TABLE IF NOT EXISTS `" . str_replace('`', '', $table_name2) . "`(
                    id mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
                    email varchar(50) NOT NULL,
                    PRIMARY KEY  (id)
                    );";
                    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
                    dbDelta($sql);
                }          
}

This code makes only one table that is the last one " *prefix_myemail ". Please suggest me or write me the accurate code to correct this issue.

Your help is appreciated in advance..


Solution

  • may be you forgot the primary key for the myentries table, try to add the primary key like this

    if( $wpdb->get_var("show tables like '$table_name1' ") != $table_name1)  
    {
    
        $sql = "CREATE TABLE IF NOT EXISTS `" . str_replace('`', '', $table_name1) . "`(
        id mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
        name varchar(50) NOT NULL,
        sub longtext NOT NULL,
        message longtext NOT NULL,        
        PRIMARY KEY  (id)           
        );";
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        dbDelta($sql);
    }