讓 PHP 程式無須執行 mysql_query('SET NAMES latin1'); 即可正確顯示資料庫之 UTF-8 中文內容, 解決中文亂碼問題
環境: CentOS 5.10 (LANG=en_US.UTF-8), mysql-server 5.0.95-5.el5_9, 資料庫內含 UTF-8 中文資料
修改 my.cnf 設定
$ su -c "vi /etc/my.cnf"
[mysql]
default-character-set=utf8
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1
default-character-set=utf8
# Disabling symbolic-links is recommended to prevent assorted security risks;
# to do so, uncomment this line:
# symbolic-links=0
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
[client]
default-character-set=utf8
重新啟動 mysql server 以重新讀取 my.cnf 設定值
$ su -c "service mysqld restart"
確認設置是否生效
$ mysql -u root -p -A mysql
mysql> show variables like 'character%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)
匯出目標資料庫, 此時仍必須加上 default-character-set=latin1 參數, 所匯出的中文內容才不會變成亂碼
$ mysqldump --default-character-set=latin1 --skip-extended-insert -u root -p mydatabase > mydatabase.sql
變更匯出內容之 SET NAMES 設定
$ sed -i -e 's/SET NAMES latin1/SET NAMES utf8/' mydatabase.sql
重新建立資料庫
$ mysql -u root -p -A mysql
mysql> drop database mydatabase;
mysql> create database mydatabase default character set utf8 collate utf8_general_ci;
mysql> exit
匯入資料庫
$ mysql -u root -p -A mydatabase < mydatabase.sql
完成後, PHP 程式無須執行 mysql_query('SET NAMES latin1'); 即可正確顯示資料庫之 UTF-8 中文內容
Ref: [轉載]MySQL 的 "SET NAMES xxx" 字元編碼問題分析 | Vixual