Quantcast
Channel: Shoultes.net » MySQL
Viewing all articles
Browse latest Browse all 3

WordPress dbDelta Function Problems

$
0
0

For a couple of weeks I was trying to figure out why the database tables in my plugin weren’t getting updated when the plugin was installed or activated. I had recently written a function (based on this example) to create tables in my WordPress plugin. I finally narrowed it down to the dbDelta function for WordPress. After doing  a few searches on Google I came across this article which explains the the dbDelta function in detail.

Come to find out I was missing a space between a ‘‘ and a ‘(‘ as seen below.

$sql_create_table = "CREATE TABLE " . $wp_table_name . "( " . $sql . " );";

Here is how it should have looked:

$sql_create_table = "CREATE TABLE " . $wp_table_name . "  (  " . $sql . "  )  ;";

Notice the spaces highlighted in green? That was the killer. So for a while, every time I added a new field to a table in database install file. For a while I was using a function (seen below) to alter the table and add the new fields.

function add_column_if_not_exist($db, $column, $column_attr = "VARCHAR( 255 ) NULL" ){
global $wpdb;
$exists = false;
$columns = $wpdb->query("show columns from $db");
while($c = $wpdb->get_row($columns)){
if($c['Field'] == $column){
$exists = true;
break;
}
}
if(!$exists){
if (!$wpdb->query("ALTER TABLE `$db` ADD `$column`  $column_attr")){
$error = 'There was a problem adding columns to the database.';
}
}
return $error;
}

So, if you are having trouble with the dbDelta function when writing a Wrodpress plugin. Be aware of extra spaces :)

Here is more information about the dbDelta function and creating tables with plugins:

http://codex.wordpress.org/Creating_Tables_with_Plugins

http://wordpress.org/tags/dbdelta-1

http://hungred.com/how-to/wordpress-dbdelta-function/

http://designoplasty.com/2009/05/15/not-using-dbdelta-with-wordpress/


Viewing all articles
Browse latest Browse all 3

Trending Articles