7

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

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

2 回答 2

19

试试这个代码

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 );
}
于 2012-10-18T10:56:24.117 回答
5

您的创建表语法错误,应该是:

 $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

于 2012-10-18T10:37:34.533 回答