我需要在 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/