我的插件无法在WordPress 3.5中创建表格

时间:2013-01-05 作者:Emerson Maningo

您好,我有此功能来安装插件并创建数据库表:

    function sortresult_install()
{
    //install sort_search_result options to the database
    global $wpdb;
    $sortsearchtitle_db_version = \'1.0\';
    $table = $wpdb->prefix."sortsearchresult";
    $structure = "CREATE TABLE IF NOT EXISTS $table (id INT(9) NOT NULL AUTO_INCREMENT,order_valuex VARCHAR(5) NOT NULL,UNIQUE KEY id (id));";
    require_once(ABSPATH . \'wp-admin/includes/upgrade.php\');
    dbDelta($structure);
    //Save database version
    update_option("sortsearchtitle_db_version", $sortsearchtitle_db_version);
    // Insert default sorting setting that is ascending
    $wpdb->query("INSERT IGNORE INTO $table(order_valuex) VALUES(\'ASC\')");
}   
这是构造函数:

function __construct()
{

    //Register activation hook
    register_activation_hook(__FILE__,array(&$this,\'sortresult_install\'));

    //Add menu hook
    add_action( \'admin_menu\', array(&$this,\'sort_searchresults_menu\'));

    //Update function hook
    add_action(\'plugins_loaded\', array(&$this,\'sortsearchtitle_update_db_check\'));

    //Run the search function
    add_action(\'pre_get_posts\',array(&$this,\'sort_searchresult_by_title\'));

}
你知道为什么上面的函数不能创建数据库表吗?我正在为Wordpress 3.5更新这个插件。谢谢

1 个回复
最合适的回答,由SO网友:Eugene Manuilov 整理而成

首先,我想让你参考一下WP codex关于Creating or Updating the Table with Plugin. 然而,请注意,dbDelta函数相当挑剔。例如:

您必须在SQL语句中将每个字段放在自己的行上必须使用关键字key而不是其同义词索引,并且必须至少包含一个关键字这意味着问题出现在表声明中,表声明存储在$structure 变量尝试按以下方式重写:

$structure = "CREATE TABLE $table (
  id INT(9) NOT NULL AUTO_INCREMENT,
  order_valuex VARCHAR(5) NOT NULL,
  UNIQUE KEY id (id)
);";
然后您的代码将如下所示:

function sortresult_install()
{
    //install sort_search_result options to the database
    global $wpdb;

    $sortsearchtitle_db_version = \'1.0\';
    $table = $wpdb->prefix."sortsearchresult";
    $structure = "CREATE TABLE $table (
      id INT(9) NOT NULL AUTO_INCREMENT,
      order_valuex VARCHAR(5) NOT NULL,
      UNIQUE KEY id (id)
    );";

    require_once(ABSPATH . \'wp-admin/includes/upgrade.php\');
    dbDelta($structure);

    //Save database version
    update_option("sortsearchtitle_db_version", $sortsearchtitle_db_version);

    // Insert default sorting setting that is ascending
    $wpdb->query("INSERT IGNORE INTO $table(order_valuex) VALUES(\'ASC\')");
} 

结束

相关推荐