来自WordPress codex关于dbDelta:
dbDelta函数检查当前的表结构,将其与所需的表结构进行比较,并根据需要添加或修改表,因此可以非常方便地进行更新(有关如何使用dbDelta的更多示例,请参阅wp admin/upgrade-schema.php)。然而,请注意,dbDelta函数相当挑剔。例如:
您必须在SQL语句中将每个字段放在自己的行上主键和主键的定义之间必须有两个空格必须使用关键字key,而不是其同义词索引,并且必须至少包含一个关键字不得在字段名称周围使用任何撇号或反勾号有了这些注意事项,下面是函数中的下一行,它们将实际创建或更新表。您需要在$sql变量中替换您自己的表结构。
我更改了您的sql:"create table $packagetable (
对此:"CREATE TABLE " . $packagetable . " (
这是您的代码的工作副本:
global $booking_db_version;
$booking_db_version = "1.0.0";
function booking_install() {
global $wpdb;
global $booking_db_version;
global $tableprefix;
$installed_version = get_option(\'booking_db_option\');
$tableprefix = $wpdb->prefix . \'booking_\';
require_once(ABSPATH . \'wp-admin/includes/upgrade.php\');
if ( $installed_version !== $booking_db_version ) {
// Create table for packages
$packagetable = $tableprefix . \'packages\';
$sql = "CREATE TABLE " . $packagetable . " (
id INT NOT NULL AUTO_INCREMENT,
name TEXT NOT NULL,
description TEXT NOT NULL,
city1 TEXT NOT NULL,
city2 TEXT NOT NULL,
PRIMARY KEY (id)
) ". $charset_collate .";";
dbDelta($sql);
// Create table for hotels
$hoteltable = $tableprefix . \'hotels\';
$sql = "CREATE TABLE " . $hoteltable . " (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name text NOT NULL,
city text NOT NULL,
price decimal(10,2) NOT NULL,
PRIMARY KEY (id)
) ". $charset_collate .";";
dbDelta($sql);
// Create table for addons
$addontable = $tableprefix . \'addons\';
$sql = "CREATE TABLE " . $addontable . " (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name text NOT NULL,
addongroup text NOT NULL,
price decimal(10,2) NOT NULL,
PRIMARY KEY (id)
) ". $charset_collate .";";
dbDelta($sql);
// Create table for addon groups
$addongrouptable = $tableprefix . \'addon_groups\';
$sql = "CREATE TABLE " . $addongrouptable . " (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name text NOT NULL,
perhead text NOT NULL,
PRIMARY KEY (id)
) ". $charset_collate .";";
dbDelta($sql);
update_option(\'booking_db_version\', $booking_db_version);
}
}
register_activation_hook(__FILE__, \'booking_install\');