Vishnu
Vishnu

Reputation: 198

Table is not getting created when plugin activated in wordpress

I am trying to create a plugin where upon activation it needs to create a table. Below is the code that I am using to make the plugin.

register_activation_hook( __FILE__, 'so_50960355_insert_page', 
'your_plugin_options_install' );
function so_50960355_insert_page(){
    // Define my page arguments
    $page = array(
        'post_title'   => 'Menu',
        'post_content' => 'Short Code',
        'post_status'  => 'publish',
        'post_author'  => get_current_user_id(),
        'post_type'    => 'page',
    );

    wp_insert_post( $page, '' );
}


// function to create the DB / Options / Defaults                   
function your_plugin_options_install() {
    global $wpdb;
    $your_db_name = $wpdb->prefix . 'table';
    global $your_db_name;

    // create the ECPT metabox database table
    if($wpdb->get_var("show tables like '$your_db_name'") != $your_db_name) 
    {
        $sql = "CREATE TABLE " . $your_db_name . " (
        `id` mediumint(9) NOT NULL AUTO_INCREMENT,
        `apikey` mediumtext NOT NULL,
        `locid` mediumtext NOT NULL,
        `appid` mediumtext NOT NULL,
        UNIQUE KEY id (id)
        );";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

I have found this in debug.log. In this debug.log Line 1 of SQL code is repeated in Line 3 also. Where in original code it was different.

 WordPress database error You have an error in your SQL syntax; check the 
manual that corresponds to your MySQL server version for the right syntax to 
use near '(
        `id` mediumint(9) NOT NULL AUTO_INCREMENT,
        `apikey` mediumtext' at line 1 for query CREATE TABLE  (
        `id` mediumint(9) NOT NULL AUTO_INCREMENT,
        `apikey` mediumtext NOT NULL,
        `locid` mediumtext NOT NULL,
        `appid` mediumtext NOT NULL,
        UNIQUE KEY id (id)
        ) made by activate_plugin,

Upvotes: 1

Views: 118

Answers (2)

Vishnu
Vishnu

Reputation: 198

I found the problem is with the Mysql Version I am using. I am trying to upgrade the version and Update the answer here.

Upvotes: 0

anmari
anmari

Reputation: 4153

It is probably not firing that hook because it is the third parameter. The codex says it expects one callback. It doesn't appear to allow for > 1 callback at a time. See https://codex.wordpress.org/Function_Reference/register_activation_hook Change code to

register_activation_hook( __FILE__, 'so_50960355_insert_page');
register_activation_hook( __FILE__, 'your_plugin_options_install' ); 

Upvotes: 2

Related Questions