WordPress.org

Support

Support » Plugins and Hacks » Plugin not creating table on activation.

Plugin not creating table on activation.

  • Greetings,

    I’m developing my first plugin, but am running into issues with the plugin not creating the table in my database, when I initialize it. I know that its being called, because the option is added into my wp_options folder. I’m baffled as to why this isn’t working, so your help is very much appreciated.

    The method is below:
    // Activate Plugin
    register_activation_hook(__FILE__,’init_database’);

    function init_database() {
    global $wpdb, $table_prefix;
    global $favoritethis_db_version;
    $table_name = $table_prefix.”favorites”;

    if ($wpdb->get_var(“show tables like ‘$table_name'”) != $table_name) {
    require_once(ABSPATH . ‘wp-admin/upgrade-functions.php’);
    dbDelta(“CREATE TABLE” . $table_name . ” (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    post_id mediumint(9) NOT NULL default ‘0’,
    PRIMARY KEY (id)
    );”);

    add_option(“favoritethis_db_version”, “1.0”);
    }
    }

Viewing 3 replies - 1 through 3 (of 3 total)
  • use maybe_create_table() it is found in wp-admin/upgrade.php just include it into that function

    I found the issue in my code. CREATE TABLE did not have a space before the table name, so the SQL query was failing. WordPress wasn’t informing me of that. For the Google Gods, here’s my finished code:

    // Activate Plugin

    register_activation_hook(__FILE__,’init_database’);

    function init_database() {

    global $wpdb, $table_prefix;

    global $favoritethis_db_version;

    $table_name = $table_prefix.”favorites”;

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

    require_once(ABSPATH . ‘wp-admin/upgrade-functions.php’);

    $sql = "CREATE TABLE " . $table_name . " (id mediumint(9) NOT NULL AUTO_INCREMENT, post_id<code>mediumint(9) NOT NULL default '0', PRIMARY KEY (</code>id

    ));”;

    maybe_create_table($table_name, $sql);
    add_option("favoritethis_db_version", "1.0");
    }
    }

    lesson learned: a good night’s sleep always fixes annoying bugs!

    the path for upgrade-functions.php has changed in WP2.3.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Plugin not creating table on activation.’ is closed to new replies.
Skip to toolbar