1

I am trying to create a database table within a my wordpress plugin main file. Here is my code to create the database table. When I activate the plugin from Wordpress control panel, plugin activate but database tables doesn't create.

     <?php   
     function keywords_ranker_install() {
 global $wpdb;
 global $keyword_rankerdb;
 $keyword_rankerdb = "1.0";
 $table_name = $wpdb->prefix . "search_engine";

        if($wpdb->get_var("SHOW TABLES LIKE '$table_name'")!= $table_name) {

        $sql = "CREATE TABLE IF NOT EXISTS ".$table_name." (
        id int(11) NOT NULL AUTO_INCREMENT,
        engine text NOT NULL,
        PRIMARY KEY ('id'));";

    //reference to upgrade.php file
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta($sql);
    //$wpdb->query($sql);

    //update_option('keyword_ranker_version',$keyword_rankerdb);
    }
  //action hook for plugin activation 

   }//end of plugin installation
      register_activation_hook(__FILE__,'keywords_ranker_install' );

?>

I'm not sure what I'm missing, and any help would be much appreciated!

1 Answer 1

1

Your syntax is wrong and this IF NOT EXISTS is not needed because your condition is already checking that.

NOTE: I switched it to all single quotes so its easier to follow and removed the single quotes in (id);

function keywords_ranker_install() {
global $wpdb;
global $keyword_rankerdb;
$keyword_rankerdb = "1.0";
$table_name       = $wpdb->prefix . "search_engine";

if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) != $table_name ) {

    $sql = 'CREATE TABLE ' . $table_name . ' (
    id int(11) NOT NULL AUTO_INCREMENT,
    engine text NOT NULL,
    PRIMARY KEY (id))';

    //reference to upgrade.php file
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );

    //update_option('keyword_ranker_version',$keyword_rankerdb);
}
//action hook for plugin activation

}

//end of plugin installation
register_activation_hook( __FILE__, 'keywords_ranker_install' );
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your help @topdown. I think I need to rework on my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.