Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying To Create New Wordpress Database Table

Just trying to create a new database table on plugin activation. For the love of life I cannot figure out why this will not work.

function super_simple_photo_activate() {
global $wpdb;
$table_name = $wpdb->prefix."super_simple_photo_options";
if ($wpdb->get_var('SHOW TABLES LIKE '.$table_name) != $table_name) {
    $sql = 'CREATE TABLE '.$table_name.'(
        thumbs_max VARCHAR(3),
        image_max VARCHAR(4),
        image_quality VARCHAR(3),
        PRIMARY KEY  (id))';

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

    add_option("super_simple_photo_db_version", "1.0");
}
}
register_activation_hook(__FILE__, 'super_simple_photo_activate');

I've spent at least 5 hours tinkering with this but with no luck, no error either on activation.

What did the trick - id INTEGER NOT NULL - thanks t.thielemans

$sql = 'CREATE TABLE '.$table_name.'(
        id INTEGER NOT NULL,
        thumbs_max VARCHAR(3),
        image_max VARCHAR(4),
        image_quality VARCHAR(3),
        PRIMARY KEY  (id))';
like image 482
Terry Avatar asked Oct 18 '12 10:10

Terry


Video Answer


2 Answers

Try this code

register_activation_hook ( __FILE__, 'on_activate' );

function on_activate() {
    global $wpdb;
    $create_table_query = "
            CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}table1` (
              `id` bigint(20) unsigned NOT NULL default '0',
              `name` text NOT NULL,
              `address` text NOT NULL
            ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
    ";
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $create_table_query );
}
like image 66
Ratnakar - StoreApps Avatar answered Oct 07 '22 23:10

Ratnakar - StoreApps


Your create table syntax is wrong, should be:

 $sql = 'CREAT TABLE '.$table_name.'(
-----
 $sql = 'CREATE TABLE '.$table_name.'(

Edit: Define your primary key

 $sql = 'CREATE TABLE '.$table_name.'(
        id INTEGER NOT NULL,
        thumbs_max VARCHAR(3),
        image_max VARCHAR(4),
        image_quality VARCHAR(3),
        PRIMARY KEY (id))';

Bit of extra info on SQL from W3schools: http://www.w3schools.com/sql/sql_primarykey.asp

like image 24
CustomX Avatar answered Oct 07 '22 22:10

CustomX