Wordpress Database Check Function

Ok. So here is a little snippet of code I used for a project that was developed in Wordpress. This snippet will work for plugins mainly, to create and manage database versioning. I've used this sort of function in other projects as well and it works well for keeping track and synchronization between current database version and actual database version installed.

This version is not the final version but it is at a point where I thought it could be useful to others as a guideline to getting a plugin setup (plugin with need for seperate database table).

Notes:

  1. Anywhere the word 'plugin' or 'PLUGIN' is used, replace with a unique prefix for your plugin.
  2. In my actual setup, I have a settings page for my plugin, which is used to post the 'check_db_version' which allows the script to dive into the database check function for updating fields. I call this function on each page load however, to ensure that my plugin table is created.
  3. This can also be globalized and used for all plugins with the need to create a database by passing in the $plugin_table and $plugin_fields to the function eg. function check_db_table($table = 'plugin_table', $plugin_fields = array()) 
  4. Fields are checked to ensure that they exist in the table, that they have the correct data_type and max length and that the null attribute is correctly set to 'YES' if needed.
  5. The last part of the function removes orphan fields from the table and has a required 'remove_orphans' input field to ensure that orphan fields are only removed after the user has a chance to backup or ensure that those fields are no longer needed.

 



/**
 * Check that database table exists and create if it doesn't
 **/
function check_db_table () {
    global $wpdb;

    $plugin_fields = array(
        'item'=>'VARCHAR(100) NULL',
        'name'=>'VARCHAR(100) NULL',
        'created'=>'datetime null',
        'updated'=>'datetime null',
    );

    // Check that table exists in the database
    if($wpdb->get_var("show tables like '".PLUGIN_TABLE."'") != PLUGIN_TABLE) {
        //if table is not found, build sql to create it
        $sql[] = 'create table '.PLUGIN_TABLE.' (';
        $sql[] = 'id mediumint(9) not null primary key auto_increment,';
        foreach($plugin_fields as $key=>$val)
            $fields[] = "$key $val,";

        if(isset($fields))
            $sql[] = join(NULL, $fields);

        $sql[] = 'UNIQUE KEY item (item)';

        $sql[] = ')';

        // Create table and add option to the database
        $wpdb->query(join(NULL, $sql));
        add_option("plugin_db_version", PLUGIN_DB_VERSION);
        add_option("plugin_version", PLUGIN_VERSION);

    }
    elseif(isset($_POST['check_db_version']))
    {
        // Check the version and compatibility of the cobrand table
        $table_fields = $wpdb->get_results("select column_name, data_type, is_nullable, character_maximum_length from information_schema.columns
where table_name = '".PLUGIN_TABLE."'");

        foreach($table_fields as $table_field)
            $actual_fields[$table_field->column_name] = $table_field;

        unset($actual_fields['id']);

        $del = NULL;
        foreach($plugin_fields as $key=>$val)
        {
            $sql = 'alter table '.PLUGIN_TABLE;
            if(!isset($actual_fields[$key]))
            {
                $fields[] = "$del add column $key $val";
                if(isset($lastfield))
                $fields[] = " after $lastfield";
                $report[] = "$key added to table";
                $del = ',';
            }
            elseif($actual_fields[$key]->is_nullable == 'NO' && (strpos($val, 'not null') === false))
            {
                $fields[] = "$del CHANGE column $key $key $val";
                $report[] = "'$key' field changed";
                $del = ',';
            }
            elseif(
                strpos(strtolower($val), $actual_fields[$key]->data_type) === false
                || ($actual_fields[$key]->character_maximum_length > 0 &&
                    strpos($val, "({$actual_fields[$key]->character_maximum_length})") === false)
            )
            {
                $fields[] = "$del modify column $key $val";
                $report[] = "'$key' field updated";
                $del = ',';
            }

            unset($actual_fields[$key]);

            $lastfield = $key;
        }

        update_option("plugin_db_version", PLUGIN_DB_VERSION);
        update_option("plugin_version", PLUGIN_VERSION);

        if(isset($fields))
        {
            // Update the table if there are changes
            $query = $sql.join(NULL, $fields);
            $wpdb->query($query);

            echo '<div class=\'updated\'>Plugin table updated to version '.PLUGIN_DB_VERSION.'.</div>';
            echo '<div class=\'updated\'>'.join('<br />', $report).'</div>';
        }
        else
            echo '<div class=\'updated\'>Plugin database version is up to date - '.PLUGIN_DB_VERSION.'.</div>';

        if(count($actual_fields) > 0)
        {
            $orp_del = NULL;
            foreach($actual_fields as $field)
            {
                $orphans[] = "$orp_del drop column ".$field->column_name;
                $orphans_list[] = $field->column_name;
                $orp_del = ',';
            }

            if(isset($_POST['remove_orphans']))
            {
                $orphan_sql = 'alter table '.PLUGIN_TABLE;

                $wpdb->query($orphan_sql.join(NULL, $orphans));
                update_option("plugin_has_orphan_fields", 0);
                echo '<div class=\'updated\'>Orphan fields removed: '.join(', ', $orphans_list).'.</div>';
            }
            else
            {
                add_option("plugin_has_orphan_fields", 1);
                echo '<div class=\'error\'>Orphan fields found: '.join(', ', $orphans_list).'</div>';
            }
        }
    }

}

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
Share

 

 

Blogs

LinzSloan.Net
Modeling profile of Lindsay Sloan... a Diva

My Two Cents
Lori Oswald's Blog
Lori Oswald's Blog

AdamNutting.Com
Learn some more about the NetNutt

Jay Adkins Online Blog
Father, Husband... GEEK

Patrick Thurmond's Blog
Thoughs, rants and influential creations

Business Links

New Millennium Tecknology
Custom Website Design & Development

Teck Interactive Media
Online marketing and advertising

Other:

Senior Year Basketball Stats
(Just for the records so we can remember)

Donovan Thompson - Park University Alumni 2006

June 2011 Posts

Pear Upgrade: Security Error Fix

April 2011 Posts

MyWi & Pocket Proxy

February 2011 Posts

Wordpress Database Check Function

December 2010 Posts

Handy Little Adwords Tracking Trick
Setting up a New Linux Developer Box

August 2010 Posts

Moving on to New Technologies

June 2010 Posts

Clearing All Favicons in Firefox
LDAP Integration w/Drupal 5.x

March 2010 Posts

More Grief About CMSs

December 2009 Posts

DVD Codec Pack
PERL Word Suggestion function 11 Lines of Code
Ajax/JQuery File Upload
Ajax Star Rating Script