php - 使用 dbDelta 函数在 Wordpress 中创建表

标签 php mysql wordpress

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

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

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

-将每个字段放在一个新行上
-在主键和它的定义之间放置两个空格
-至少有一把 key

代码如下:

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

有什么想法吗?

最佳答案

不要硬编码表名,使用 $wpdb->prefix(正如其他人所说)。

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

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

Note that the dbDelta function is rather picky, however. For instance:

  • 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.

关于php - 使用 dbDelta 函数在 Wordpress 中创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9957836/

相关文章:

php - 拉维尔 : Eager loading pivot table and sorting on pivot table field

php - 从两个表中选择,其中每个表中的不同列等于 $id ORDER BY 公共(public)列 (PHP/MySQL)

php - Laravel 5.3 Eloquent where 从父模型连接表的子句

java - 将blob图像转换为数组以在spring mvc中的网页中显示

javascript - WordPress 中的 anchor 链接

php - 如何在使用 Laravel 的 block 功能时延迟脚本的执行?

php - 变量转储不显示

php - 检查 PHP mysql 查询字段中的逗号分隔值

php - Jquery 变量返回 null

css - WordPress中的自定义svg管理菜单图标