Creating Database Tables During Install

Your plugin is activated each time a user accesses a page. WP does not give you a simple way to track if that activation means your plugin is installed for the first time, being upgraded, or just another page access. The template code from this site differentiates these component life cycle events and gives you a place to write code for them. One such important event is installation. By installation, this actually means the first activation after install. Read about the general mechanism of add Install/Uninstall Actions. That article describes different places to put code to be executed during installation. (Also see where to put code to execute during an update in Update Actions.

The most common thing to do during installation is to create a database table that your plugin will use. There is a specific function already for this purpose. All you need to do is override it in you XXX_Plugin class.

Locate this function which should be already in your XXX_Plugin class:

To create a table, simply uncomment these three lines and change ‘mytable’ to the table name you wish to use.

Note: the “prefixTableName” function actually adds two prefixes to the table name. The function is:

1
2
3
4
5
6
7
8
9
10
11

/**
* @param $name string name of a database table
* @return string input prefixed with the WordPress DB table prefix
* plus the prefix for this plugin (lower-cased) to avoid table name collisions.
* The plugin prefix is lower-cases as a best practice that all DB table names are lower case to
* avoid issues on some platforms
*/protectedfunction prefixTableName($name){global$wpdb;return$wpdb->prefix.strtolower($this->prefix($name));}

The $wpdb->prefix is a WP convention to prefix all tables with “wp_”. This prefix can be changed on a WP installation. This allows for more than one WP installation to share the same DB by simply using different table prefixes (and hence different tables).

This template code uses the convention that things like table names and options should be prefixed with the name of the plugin (actually the “XXX” in your “XXX_Plugin”) to avoid having the same names as other plugins. The use of $this->prefixTableName(), $this->prefix() and option handling functions like $this->getOption() are convenience functions to make this prefixing somewhat transparent.

If you use $this->prefixTableName(‘mytable’) in your MyAwesomePlugin_Plugin.php file, you would end up a tabled named “wp_myawesomeplugin_mytable”. Unlike option prefixes, table name prefixes are lower-cased because mixed case table names can cause a problem when you transfer a MySQL DB content between MySQL instances on Unix and Windows.

Dropping DB Tables on Uninstall

A good plugin citizen should clean up after itself. If your plugin creates DB tables on install, it makes sense to drop them on uninstall. To do this, override your unInstallDatabaseTable() function in your XXX_Plugin class and drop your tables there.

But it is not always that simple. Sometimes when a user has a problem with a plugin, he will try uninstalling it and installing it again. He may not intend for all his data to be removed.

One way I have dealt with that in the past is to create an option for the plugin where the plugin administration can choose if the tables should be dropped on uninstall. For example, I created a “DropOnUninstall” option like this (See Handling Options)

Then I added a check in the unInstallDatabaseTable() function like what is shown commented-out in the template code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/**
* See: http://plugin.michael-simpson.com/?page_id=101
* Drop plugin-created tables on uninstall.
* Issue: sometimes people have issues with a version of the plugin and they will
* uninstall with the intention of immediately re-installing. This will cause loss of
* data. Good practice is to set an option for whether or not to drop tables on uninstall
* @return void
*/protectedfunction unInstallDatabaseTables(){// // if you use this 'DropOnUninstall' be sure to add it to the array in getOptionMetaData()// and you should also guard deleteSavedOptions()// if ('true' === $this->getOption('DropOnUninstall', 'false')) {// global $wpdb;// $tableName = $this->prefixTableName('mytable');// $wpdb->query("DROP TABLE IF EXISTS `$tableName`");// }}

/**
* See: http://plugin.michael-simpson.com/?page_id=101
* Drop plugin-created tables on uninstall.
* Issue: sometimes people have issues with a version of the plugin and they will
* uninstall with the intention of immediately re-installing. This will cause loss of
* data. Good practice is to set an option for whether or not to drop tables on uninstall
* @return void
*/
protected function unInstallDatabaseTables() {
// // if you use this 'DropOnUninstall' be sure to add it to the array in getOptionMetaData()
// and you should also guard deleteSavedOptions()
// if ('true' === $this->getOption('DropOnUninstall', 'false')) {
// global $wpdb;
// $tableName = $this->prefixTableName('mytable');
// $wpdb->query("DROP TABLE IF EXISTS `$tableName`");
// }
}

That did not seem to fix anything. There are two identical functions for each install db and uninstall db. One is in XXX_plugin.php and the other in XXX_LifeCycle.php

Changing either does not seem to get my database made. Its very weird. So far everything has been amazing with this template.. just stuck because everything looks like it should work fine, but I can not get any feed back from the install procedure.

XXX_LifeCycle.php defines empty functions and calls them. XXX_Plugin.php is a subclass (Object Oriented) so it inherits those functions. The intention is that you would not change XXX_LifeCycle but would redefine (override) the functions in XXX_Plugin so those get called instead. Perhaps you broke something in XXX_LifeCycle? The XXX_init.php gets run by WordPress, which then runs XXX_Plugin’s install(), activate(), deactivate() as appropriate. XXX_Plugin’s install() is really in XXX_LifeCycle (it inherits it). That function calls others like installDatabaseTables() which you can redefine in XXX_Plugin.

You might try setting up a logging message in installDatabaseTables() to see if it gets called, and perhaps print out the results of your database call in case there is an error.

What I found, concerning this issue.
1. Uninstall functionality hasn’t built in template – I see no ‘register_uninstall_hook’ in files.
2. I was confusing terms Deactivate and Uninstall. Deactivation doesn’t cause tables cleanup.
3. First activation of a plugin precedes by installation – that’s the time when install callbacks run.
3. When you write normal mysql dump in installDatabaseTables()
$wpdb->query(“DROP TABLE IF EXISTS `wp_antiddos`;
CREATE TABLE IF NOT EXISTS `wp_tablename`…”);
CREATE TABLE do not executed. Write 2 query() calls instead.
4. When you have NOT created tables (see before) none of Activation do NOT involve install callbacks.
5. You can run Installation again – you should manually
select * from wp_options where option_name rlike ‘_installed’
find there your plugin’s option and delete it.