WordPress创建数据库不工作

时间:2017-05-01 作者:CompactCode

所以我试图建立一个数据库,用于在add_menu_page(). I\'m using this on a custom parent theme

现在我已经有了这个(目前在我的functions.php):

function countriesDB_init()
{
    global $wpdb;
    $table_name = $wpdb->prefix . \'designitcountries\';

    //create table (if it doesnt exist)

    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE" . " " . $table_name . "(
  id mediumint(9) NOT NULL AUTO_INCREMENT,
  time datetime DEFAULT \'0000-00-00 00:00:00\' NOT NULL,
  name tinytext NOT NULL,
  text text NOT NULL,
  url varchar(55) DEFAULT \'\' NOT NULL,
  PRIMARY KEY  (id)
) $charset_collate;";

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

        $name = \'Sukru Kintas\';
        $title = \'President\';
        $country = \'World all hapkido association\';

        $wpdb->insert(
            $table_name,
            array(
                \'time\' => current_time(\'mysql\'),
                \'title\' => $title,
                \'name\' => $name,
                \'country\' => $country
            )
        );
}
do_action( \'after_switch_theme\', \'countriesDB_init\' );
当数据库表还不存在时,它应该创建一个数据库表。但它什么都没做。尚未创建数据库表。

WP_DEBUG log

WordPress database-fout: [Table \'ID203293_lacroix.wp_designitcountries\' doesn\'t exist]
SELECT COUNT(word) AS occurrence, word FROM `wp_designitcountries` GROUP BY word ORDER BY occurrence DESC

WordPress database-fout: [Table \'ID203293_lacroix.wp_designitcountries\' doesn\'t exist]
SELECT COUNT(word) AS occurrence, word FROM `wp_designitcountries` GROUP BY word ORDER BY occurrence DESC

WordPress database-fout: [Table \'ID203293_lacroix.wp_designitcountries\' doesn\'t exist]
SELECT COUNT(word) AS occurrence, word FROM `wp_designitcountries` GROUP BY word ORDER BY occurrence DESC

WordPress database-fout: [Table \'ID203293_lacroix.wp_designitcountries\' doesn\'t exist]
SELECT COUNT(word) AS occurrence, word FROM `wp_designitcountries` GROUP BY word ORDER BY occurrence DESC

WordPress database-fout: [Table \'ID203293_lacroix.wp_designitcountries\' doesn\'t exist]
SELECT COUNT(word) AS occurrence, word FROM `wp_designitcountries` GROUP BY word ORDER BY occurrence DESC

WordPress database-fout: [Table \'ID203293_lacroix.wp_designitcountries\' doesn\'t exist]
SELECT COUNT(word) AS occurrence, word FROM `wp_designitcountries` GROUP BY word ORDER BY occurrence DESC

1 个回复
最合适的回答,由SO网友:Jeffrey von Grumbkow 整理而成

dbDelta() 非常挑剔,下面我已经检查了requirements 对于dbDelta() 在代码中。正如您在下面看到的,您的代码没有满足其中两个要求,这很可能会阻止dbDelta() 创建表。

您必须在SQL语句中将每个字段放在自己的行上。CHECKCHECK 必须使用关键字key而不是其同义词索引,并且必须至少包含一个关键字。N/AN/ACHECK字段类型必须全部为小写FAILCHECKFAIL

另请参见文档:

dbDelta函数检查当前表结构,将其与所需的表结构进行比较,并根据需要添加或修改表

因此,您的初始检查if($wpdb->get_var("SHOW TABLES LIKE \'$table_name\'") != $table_name) { 冗余为dbDelta() 这是为你做的。