WordPress.org

Ready to get started?Download WordPress

Forums

Plugin not creating table on activation. (4 posts)

  1. carpeaqua
    Member
    Posted 6 years ago #

    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");
    }
    }

  2. Lester Chan
    Member
    Posted 6 years ago #

    use maybe_create_table() it is found in wp-admin/upgrade.php just include it into that function

  3. carpeaqua
    Member
    Posted 6 years ago #

    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!

  4. Lester Chan
    Member
    Posted 6 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic