Problem in creating table through plugin code

The above code should be placed in a function and then hook that with plugin activation hook? Here’s sample structure of plugin-name.php file.

Note –

  • Use CREATE TABLE IF NOT EXISTS instead only create table

Code Updated on – 2012-08-04

<?php // this code goes into your my_plugin_name.php file

function install_my_plugin() {

    global $wpdb;
    $table_name = "tbllb_club";

    //the SQL commands to create table
    $sql = "SQL_QUERY_1";
    $sql .= "SQL_QUERY_2";

    //this stuff is needed to create the table in MySQL database
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);

    //optional 
    add_option("my_plugin_version", "1.0");
}

//lets get it hooked to plugin activation
register_activation_hook(__FILE__,'install_my_plugin');

?>

Reference –

  • Register activation hook – Use this to do some action when plugin is activated, In this case we’r calling install_my_plugin() function to create table.