Utilize shell scripts,linux commands, open source tools,java, to Maximize the Power of Linux.
Focused on working with linux and shell, search engine technology including Chinese segmenter
Any questions please contact me at gmail: david.ullua

9/19/2008

PHP, MySQL中使用UTF-8编码,以及中文乱码的解决

若在linux/unix服务器上使用
注意如下事项:
1、设置mysql服务使用的编码:
#vi /etc/
在 [mysqld]以及[mysqld_safe]后面都加上以下两行:
default-character-set=utf8
default-collation=utf8_general_ci

然后重启mysqld服务: /etc/init.d/mysqld restart (fedora 9) 为例。
2.php的页面代码,执行sql语句前(或者在数据库连接建立后)设置本次连接的字符集,示例如下:
mysql_query("SET NAMES 'utf8'");
$result=mysql_query("select * from t_userlog");

3.Terminal登录mysql时指定字符集:
mysql --default-character utf8 -u root -pmypass
这样也可以:
mysql --default-character-set utf8 -u root -pmypass

4.apache的配置文件httpd.conf中,找到 AddDefaultCharset一行,注释掉,或者改成如下:
AddDefaultCharset off

(这一步是为了让不同字符集,比如utf-8,gbk的网页放到服务器上都可以正常在客户端显示)

5.每一个php页面中,都在head部分设定meta头的charset:
< meta equiv="Content-Type" content="text/html; charset=UTF-8" >

6. 以终端登录mysql中可以用如下sql语句来显示以character开头的变量:
SHOW VARIABLES LIKE 'character_set_database';

SHOW VARIABLES LIKE 'character_set_client';
show variables like 'character%';

可以通过 show character set; 语句来显示有哪些可用的字符集。

About Me

I am a senior developer and a team leader with 3 years development experience in Suzhou, China, focus on mobile web search, linux, Java and machine learning in NLP (natural language processing). My goal is to improve people's life with computer technology.