Inserting rows into a custom table, when plugin is activated

Trying to create a plugin that creates a custom table & populates it with a row of data, once activated. The table is created OK, but the row of data is not added. Please can someone point out what I have done wrong with the row of data?

 register_activation_hook( __FILE__, 'pu_create_plugin_tables' );
    register_activation_hook( __FILE__, 'pu_insert_custom_table' );

    function pu_create_plugin_tables()
    {
        global $wpdb;


        $table_name = $wpdb->prefix . 'countries';

        $sql = "CREATE TABLE $table_name (
          id int(11) NOT NULL AUTO_INCREMENT,
          name varchar(255) DEFAULT NULL,
          labour_cost_rate int(11) NOT NULL,
          overheads     DECIMAL(6,2) NULL,
          profit DECIMAL(6,2) NULL,
          UNIQUE KEY id (id)
              );";


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



    function pu_insert_custom_table(){

        global $wpdb;

      $welcome_id = "3";
      $welcome_name  = "helen";

      $rows_affected = $wpdb->insert( $table_name, array( 'id' => $welcome_id, 'name' => $welcome_name ));
     require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
     dbDelta( $rows_affected );

       }

Related posts

1 comment

  1. The table isn’t defined on your insert function. So you will need to add – $table_name = $wpdb->prefix . 'countries'; as you did for the create table function.

Comments are closed.