skip to Main Content

I Tried to create table in database with the help of register_activation_hook() but its not working….

function my_plugin_activation(){
    global $wpdb , $table_prefix;

    $wp_emp = $table_prefix.'emp';

    $q = "CREATE TABLE IF NOT EXISTS` $wp_emp` (`id` INT NOT NULL , `name` VARCHAR(50) NOT NULL ,
    `Email` VARCHAR(100) NOT NULL , `status` VARCHAR NOT NULL ) ENGINE = InnoDB;";
    $wpdb -> query($q);
}

2

Answers


  1. You need to add register_activation_hook in your plugin file to run any script during the activation of your plugin and call the dbDelta function to execute the sql command and include wp-admin/includes/upgrade.php. For example:

    // Must include this line
    require_once(ABSPATH.'wp-admin/includes/upgrade.php');
    
    register_activation_hook(__FILE__, function() {
        global $wpdb;
    
        $charsetCollate = $wpdb->get_charset_collate();
    
        $table = $wpdb->prefix . 'emp';
    
        if ($wpdb->get_var("SHOW TABLES LIKE '$table'") != $table) {
            $sql = "CREATE TABLE $table (
                `id` INT(11) NOT NULL,
                `name` VARCHAR(50) NOT NULL,
                `Email` VARCHAR(100) NOT NULL,
                `status` VARCHAR(50) NOT NULL
            ) $charsetCollate;";
            dbDelta($sql);
        }
    });
    
    Login or Signup to reply.
  2. First, your table name is too short, so not accepted, and you need some more things:

    register_activation_hook(__FILE__, 'my_plugin_activation');
    function my_plugin_activation() {
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); // Mandatory
    
        global $wpdb;
        
        // dbDelta function modify the database when using "CREATE TABLE".
        dbDelta("
            CREATE TABLE {$wpdb->prefix}abc_emp (
            id INT NOT NULL,
            name VARCHAR(50) NOT NULL,
            email VARCHAR(100) NOT NULL,
            status VARCHAR(100) NOT NULL
        ) {$wpdb->get_charset_collate()}");
    }
    

    Tested and works.

    Notes:

    • You don’t need "IF NOT EXISTS" with "CREATE TABLE" as is the table already exists on plugin activation, nothing will occur.
    • The Email column name should need to be in lowercase.

    Related: I'm getting "Bad request" using ajax in custom WordPress plugin

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search