Trying To Create New Wordpress Database Table

2019-06-20 08:26发布

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))';

2条回答
The star\"
2楼-- · 2019-06-20 08:53

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

查看更多
该账号已被封号
3楼-- · 2019-06-20 09:01

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 );
}
查看更多
登录 后发表回答