1

I am using the following script to add a table to the wordpress database, but nothing is happening. I am not sure what I am doing wrong.

Any advice would be much appreciated.

     function vw_postcode_checker_create_db ()
    {
        global $wpdb;
      global $tableprefix;

        // Create Table Name
        $table_name =$tableprefix . "vw_postcode_checker";

        // Write Query to add table to database
        if ($wpdb->get_var('SHOW TABLES LIKE'.$table_name) !=$table_name)
        {
                $sql = "CREATE TABLE " . $table_name . " (
                    id INTEGER(10) UNSIGNED AUTO_INCREMENT,
                    postcode  varchar(250)   NOT NULL,
                    area varchar(250)   NOT NULL
                    PRIMARY KEY (id)
                )";
    // Execute Query to Create Table
    require_once (ABSPATH . 'wp-admin/includes/upgrade.php');
                dbDelta($sql);
                add_option ('vw_postcode_checker_version', '0.1');
        }
        }
// Register table function
register_activation_hook (__FILE__,'vw_postcode_checker_create_db');
1

Try:

function vw_postcode_checker_create_db () {
    global $wpdb;

    // Create Table Name
    $table_name = $wpdb->prefix . "vw_postcode_checker";

    // Write Query to add table to database
    if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
        $sql = "CREATE TABLE $table_name (
            id INTEGER(10) UNSIGNED AUTO_INCREMENT,
            postcode  varchar(250) DEFAULT ''  NOT NULL,
            area varchar(250) DEFAULT ''  NOT NULL,
            PRIMARY KEY (id)
         );";
        // Execute Query to Create Table
        require_once (ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        add_option ('vw_postcode_checker_version', '0.1');
    }
}
// Register table function
register_activation_hook (__FILE__,'vw_postcode_checker_create_db');

Note the use of $wpdb->prefix and the closures after PRIMARY KEY (id)

https://codex.wordpress.org/Creating_Tables_with_Plugins

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.