激活插件时,使用PHP在WordPress数据库中创建两个表

时间:2015-05-01 04:43:39

标签: php sql database wordpress plugins

我的插件有问题,假设在激活时在WordPress数据库中创建一个表。我目前的代码如下:

register_activation_hook(__FILE__, 'wp_table_install');

function wp_table_install(){
global $wpdb;
global $db_version;

$sql ="CREATE TABLE IF NOT EXISTS 'st_support_tickets'
('id' mediumint(8) unsigned NOT NULL auto_increment,
'ticket_id' varchar(36) NOT NULL,
'ticket_user_id' varchar(36) NOT NULL,
'ticket_description' TEXT default NULL,
'ticket_priority' varchar(255) default NULL,
'ticket_status' varchar(255) default NULL,
'ticket_type' varchar(255) default 'Private',
PRIMARY KEY ('id')) 
AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS 'st_support_priorities' 
('id' mediumint(8) unsigned NOT NULL auto_increment,
'ticket_user_id' varchar(36) NOT NULL,
PRIMARY KEY ('id'))
AUTO_INCREMENT=1;
";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
add_option("db_version", $db_version);
}

什么阻止这些表被创建?是sql查询还是语法还是什么?

2 个答案:

答案 0 :(得分:0)

register_activation_hook(__FILE__, 'wp_table_install');

function wp_table_install(){
global $wpdb;
global $db_version;

$sql ="CREATE TABLE IF NOT EXISTS 'st_support_tickets'
('id' mediumint(8) unsigned NOT NULL auto_increment,
'ticket_id' varchar(36) NOT NULL,
'ticket_user_id' varchar(36) NOT NULL,
'ticket_description' TEXT,
'ticket_priority' varchar(255) default NULL,
'ticket_status' varchar(255) default NULL,
'ticket_type' varchar(255) default 'Private',
PRIMARY KEY ('id')) 
AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS 'st_support_priorities' 
('id' mediumint(8) unsigned NOT NULL auto_increment,
'ticket_user_id' varchar(36) NOT NULL,
PRIMARY KEY ('id'))
AUTO_INCREMENT=1;
";

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
add_option("db_version", $db_version);
}

答案 1 :(得分:0)

经过测试并且工作正常..

register_activation_hook(__FILE__, 'wp_table_install');

function wp_table_install(){
    global $wpdb;
    global $db_version;

    $charset_collate = $wpdb->get_charset_collate();

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

    $sql ="CREATE TABLE IF NOT EXISTS st_support_tickets (
          id mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
          ticket_id varchar(36) DEFAULT '' NOT NULL,
          ticket_user_id varchar(36) DEFAULT '' NOT NULL,
          ticket_description TEXT DEFAULT '' NOT NULL,
          ticket_priority varchar(255) DEFAULT '' NOT NULL,
          ticket_status varchar(255) DEFAULT '' NOT NULL,
          ticket_type varchar(255) DEFAULT 'Private' NOT NULL,
          PRIMARY KEY (id)) $charset_collate;";

    dbDelta( $sql );

    $sql="CREATE TABLE IF NOT EXISTS st_support_priorities ( 
         id mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
         ticket_user_id varchar(36) DEFAULT '' NOT NULL,
         PRIMARY KEY (id)) $charset_collate;";

    dbDelta($sql);

    add_option("db_version", $db_version);
}