试图创建新的Wordpress数据库表

时间:2012-10-18 10:32:30

标签: database wordpress wordpress-plugin

尝试在插件激活时创建新的数据库表。 为了对生活的热爱,我无法弄清楚为什么这不起作用。

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

我花了至少5个小时修补这个但没有运气,也没有错误激活。

诀窍是什么 - id INTEGER NOT NULL - 谢谢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 个答案:

答案 0 :(得分:12)

试试此代码

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

答案 1 :(得分:5)

您的create table语法错误,应为:

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

编辑:定义主键

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

来自W3schools的SQL的额外信息:http://www.w3schools.com/sql/sql_primarykey.asp