WordPress数据库字符集/校对

时间:2012-11-23 作者:Tom J Nowell

有没有一种简单的方法可以在WordPress中获取DB表的字符集和排序规则,而不必求助于SQL查询?

2 个回复
最合适的回答,由SO网友:fuxia 整理而成

$wpdb->charset$wpdb->collate. 我不确定这些值中的一个是否为空或何时为空,因此最好为空值做好准备…

从我的DB类:

/**
 * Get table charset and collation.
 *
 * @since  2012.10.22
 * @return string
 */
protected static function get_wp_charset_collate() {

    global $wpdb;
    $charset_collate = \'\';

    if ( ! empty ( $wpdb->charset ) )
        $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";

    if ( ! empty ( $wpdb->collate ) )
        $charset_collate .= " COLLATE $wpdb->collate";

    return $charset_collate;
}
用于创建如下表:

    global $wpdb;

    // encoding
    $charset_collate = self::get_wp_charset_collate();
    $table           = self::get_table_name();

    // the user could have just deleted the plugin without running the clean up.
    $sql = "CREATE TABLE IF NOT EXISTS $table (
        ID bigint unsigned NOT NULL auto_increment,
        event_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        event_group tinytext,
        event_title text,
        PRIMARY KEY  (ID)
    ) $charset_collate;";


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

    dbDelta( $sql );
相关:Problem with blog charset UTF-7

SO网友:Stephen Harris

文件wp-admin/includes/upgrade.php 包括wp-admin/includes/schema.php. 顶部声明为全局(see source):

// Declare these as global in case schema.php is included from a function.
 global $wpdb, $wp_queries, $charset_collate;
...
$charset_collate = \'\';

if ( ! empty( $wpdb->charset ) )
    $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if ( ! empty( $wpdb->collate ) )
    $charset_collate .= " COLLATE $wpdb->collate";
所以你可以按照@Toscho的答案进行检查$wpdb. 或者,以托肖为例:

global $wpdb, $charset_collate;
require_once ABSPATH . \'wp-admin/includes/upgrade.php\';

$sql = "CREATE TABLE $table (
    ID bigint unsigned NOT NULL auto_increment,
    event_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    event_group tinytext,
    event_title text,
    PRIMARY KEY  (ID)
) $charset_collate;";

dbDelta( $sql );
请注意IF NOT EXISTS 不需要as dbDelta() handles this.

结束