【问题标题】:Creating Table in Wordpress with dbDelta function使用 dbDelta 函数在 Wordpress 中创建表格
【发布时间】:2012-04-15 00:22:51
【问题描述】:

我需要在 wordpress 中为插件创建一个自定义表格。我关注了一些在线文本并创建了表,但发现无法访问它。当尝试从表中选择所有内容时,不会返回任何内容,当尝试使用数据库浏览器插件查看表时,我收到此错误:“您的 SQL 语法有错误;请查看与您的 MySQL 服务器相对应的手册在第 1 行的“FROM wp-typeEvents LIMIT 0, 100”附近使用正确语法的版本,以响应插件的查询(“SELECT SQL_CALC_FOUND_ROWS FROM wp-typeEvents LIMIT 0, 100;;”)。

简而言之,我正在尝试使用 dbDelta 创建一个表。该表已创建,但存在某种问题,使其无法添加行或读取其内容。

我读到 dbDelta 可以是 finnicky 函数,所以我试图坚持它的三个黄金法则:

-将每个字段放在一个新行上
-在主键及其定义之间放置两个空格
- 至少有一把钥匙

代码如下:

global $wpdb;

$tablename = "wp-typeEvents";   
$query = "CREATE TABLE `" . $tablename . "` (
    `id` mediumint(9) NOT NULL AUTO_INCREMENT,
    `eventName` varchar(60) NOT NULL,
    `location` varchar(60) DEFAULT '' NULL,
    `price` double NOT NULL,
    `description` text NOT NULL,
    `paypal` varchar(60) NOT NULL,
    PRIMARY KEY  (`id`)
    );";

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

有什么想法吗?

【问题讨论】:

  • 想出了我自己的问题。该函数被表名中的连字符卡住了。

标签: php mysql wordpress


【解决方案1】:

不要对表名进行硬编码,使用 $wpdb->前缀(正如其他人所指出的那样)。

不要在字段名称周围使用引号。

还有其他有用的“规则”,它们都列在这里: http://codex.wordpress.org/Creating_Tables_with_Plugins

但是请注意,dbDelta 函数相当挑剔。例如:

  • 您必须在 SQL 语句中将每个字段放在自己的行中。
  • PRIMARY KEY 和主键定义之间必须有两个空格。
  • 您必须使用关键字 KEY 而不是其同义词 INDEX,并且您必须至少包含一个 KEY。
  • 不得在字段名称周围使用任何撇号或反引号。
  • 字段类型必须全部小写。
  • SQL 关键字,如 CREATE TABLE 和 UPDATE,必须大写。

【讨论】:

    【解决方案2】:

    如果它在插件内部,则 require_once() 路径是错误的。应该是:

    require_once('/includes/upgrade.php');
    

    应该更正以能够加载 dbDelta() 函数。

    希望这会有所帮助。

    【讨论】:

    • require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); 是正确的。
    • 插件函数是在插件加载的时候从wp-admin目录调用的,所以不需要写全路径。
    • @ninty9notout:现在我明白你的意思了:这就是问题的路径。我不认为我回答时是这样的,但我不记得了。无论如何,感谢您的注意。
    【解决方案3】:

    还要注意当前的dbDelta()函数不解析它所引用的列的UNIQUE KEY名称上的排序关键字ASC|DESC,它会将约束添加到剩余索引中,因此它会尝试添加触发唯一键错误的约束。请看下面的例子:

    尝试创建这个 questrong 文本会触发错误。

    CREATE TABLE wp_test (
            id int(11) NOT NULL AUTO_INCREMENT,
            email varchar(100) NOT NULL,
            PRIMARY KEY  (stcr_id),
            UNIQUE KEY uk_email (subscriber_email ASC))
    ENGINE = InnoDB
    DEFAULT CHARACTER SET utf8;
    

    默认情况下,排序类型是 ASC,因此可以去掉它。

    CREATE TABLE wp_test (
            id int(11) NOT NULL AUTO_INCREMENT,
            email varchar(100) NOT NULL,
            PRIMARY KEY  (stcr_id),
            UNIQUE KEY uk_email (subscriber_email))
    ENGINE = InnoDB
    DEFAULT CHARACTER SET utf8;
    

    我在 WordPress 4.1.1 上对此进行了测试

    【讨论】:

      【解决方案4】:

      我在使用 wordpress 的 dbDelta 核心功能时遇到了一些问题,并决定为其创建一个函数:

      /**
       * Prevents unnecessary re-creating index and repetitive altering table operations when using WordPress dbDelta function
       *
       * Usage Example:
       *
       * $table_name      = "ratings";
       *
       * $table_columns   = "id INT(6) UNSIGNED AUTO_INCREMENT,
       *                  rate tinyint(1) NOT NULL,
       *                  ticket_id bigint(20) NOT NULL,
       *                  response_id bigint(20) NOT NULL,
       *                  created_at TIMESTAMP";
       *
       * $table_keys      = "PRIMARY KEY (id),
       *                  KEY ratings_rate (rate),
       *                  UNIQUE KEY ratings_response_id (response_id)";
       *
       * create_table($table_name, $table_columns, $table_keys);
       *
       * Things that need to be considered when using dbDelta function :
       *
       * You must put each field on its own line in your SQL statement.
       * You must have two spaces between the words PRIMARY KEY and the definition of your primary key.
       * You must use the key word KEY rather than its synonym INDEX and you must include at least one KEY.
       * You must not use any apostrophes or backticks around field names.
       * Field types must be all lowercase.
       * SQL keywords, like CREATE TABLE and UPDATE, must be uppercase.
       * You must specify the length of all fields that accept a length parameter. int(11), for example.
       *
       * Further information can be found on here:
       *
       * http://codex.wordpress.org/Creating_Tables_with_Plugins
       *
       * @param $table_name
       * @param $table_columns
       * @param null $table_keys
       * @param null $charset_collate
       * @version 1.0.1
       * @author Ugur Mirza Zeyrek
       */
      function create_table($table_name, $table_columns, $table_keys = null, $db_prefix = true, $charset_collate = null) {
          global $wpdb;
      
          if($charset_collate == null)
              $charset_collate = $wpdb->get_charset_collate();
          $table_name = ($db_prefix) ? $wpdb->prefix.$table_name : $table_name;
          $table_columns = strtolower($table_columns);
      
          if($table_keys)
              $table_keys =  ", $table_keys";
      
          $table_structure = "( $table_columns $table_keys )";
      
          $search_array = array();
          $replace_array = array();
      
          $search_array[] = "`";
          $replace_array[] = "";
      
          $table_structure = str_replace($search_array,$replace_array,$table_structure);
      
          $sql = "CREATE TABLE $table_name $table_structure $charset_collate;";
      
          // Rather than executing an SQL query directly, we'll use the dbDelta function in wp-admin/includes/upgrade.php (we'll have to load this file, as it is not loaded by default)
          require_once (ABSPATH . 'wp-admin/includes/upgrade.php');
      
          // The dbDelta function examines the current table structure, compares it to the desired table structure, and either adds or modifies the table as necessary
          return dbDelta($sql);
      }
      

      https://github.com/mirzazeyrek/wordpress_create_table

      【讨论】:

        【解决方案5】:

        除了您自己发现的问题外,您似乎还在对表前缀进行硬编码。你不应该这样做。相反,根据手册,您应该使用:-

        $wpdb->prefix
        

        这会存储前缀并且应该添加到表名之前。这允许前缀更改的可能性。

        http://codex.wordpress.org/Creating_Tables_with_Plugins

        【讨论】:

          猜你喜欢
          • 2018-07-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-20
          • 1970-01-01
          • 1970-01-01
          • 2015-01-23
          • 2014-08-29
          相关资源
          最近更新 更多