Total Pageviews

Wednesday 22 February 2012

解决PHP的MySQL UTF-8问题

为了让PHP + Mysql工作在UTF-8
1. 数据库:
CREATE DATABASE db_name
 CHARACTER SET utf8
 DEFAULT CHARACTER SET utf8
 COLLATE utf8_general_ci
 DEFAULT COLLATE utf8_general_ci
 ;

或者如果数据库已经创建:
ALTER DATABASE db_name
 CHARACTER SET utf8
 DEFAULT CHARACTER SET utf8
 COLLATE utf8_general_ci
 DEFAULT COLLATE utf8_general_ci
 ;

CREATE TABLE table_name(
 ...
 )
 DEFAULT CHARACTER SET utf8
 COLLATE utf8_general_ci;
或者,如果已经创建的表:
ALTER TABLE tbl_name
 DEFAULT CHARACTER SET utf8
 COLLATE utf8_general_ci
 ;
2.在php.ini中启用这一行:
extension=php_mbstring.dll
在同一文件中的配置如下:
mbstring.language = Neutral
mbstring.internal_encoding = UTF-8
mbstring.encoding_translation = On
mbstring.http_input = auto
mbstring.http_output = UTF-8
mbstring.detect_order = auto
mbstring.substitute_character = none
default_charset = UTF-8
3.使用下面的PHP函数来代替:
mail()                -> mb_send_mail()
strlen()              -> mb_strlen()
strpos()              -> mb_strpos()
strrpos()             -> mb_strrpos()
substr()              -> mb_substr()
strtolower()          -> mb_strtolower()
strtoupper()          -> mb_strtoupper()
substr_count()        -> mb_substr_count()
ereg()                -> mb_ereg()
eregi()               -> mb_eregi()
ereg_replace()        -> mb_ereg_replace()
eregi_replace()       -> mb_eregi_replace()
split()               -> mb_split()
htmlentities($var)    -> htmlentities($var, ENT_QUOTES, 'UTF-8')
4.使用页眉和meta标签,如:
header('Content-type: text/html; charset=UTF-8') ;

5.数据库中的任何插入/更新之前,您应该执行下列步骤:
mysql_query("SET NAMES 'utf8'");

No comments:

Post a Comment