編輯網頁碰到中文亂碼是件很頭痛的事情,牽扯到網頁的編碼。
今天用phpmyadmin向mysql錄入中文資料的時候又碰到這類麻煩問題了。寫好的php頁面從mysql讀取出來的資料全成了火星文。老規矩網上google一下,弄了一天終于解決問題了。網上出現同類問題的兄弟很多,現在把我總結的方法拿出來分享
關于為什麼會出現亂碼台灣的 http://www.adsenseor.com/mysql/256.html 講的很詳細。我就跳過很多廢話,直奔問題所在了。
mysql字元集預設的是latin1,通過phpmyadmin錄入的utf8編碼的資料都會以latin1的編碼方式進行再編碼,而破壞了原來的資料編碼,是以無論你将浏覽器的頁面字元編碼更改成哪種方式都還是亂碼。
更改mysql的預設編碼方式,可以用指令行進行改變。而我選擇通過改變 mysql 全局變量 /etc/my.cnf (linux系統,windows環境 找my.ini),在 Unix/inux平台上, MySQL忽略人人可寫的配置檔案。這是故意的,是一個安全措施。
mysql安裝完成後(我是源碼編譯安裝的),在/mysql/surrport-script的目錄下有my-small.cnf等。分别是:
my-small.cnf:
1 # Example MySQL config file for small systems.
2 #
3 # This is for a system with little memory (<= 64M) where MySQL is only used
4 # from time to time and it's important that the mysqld daemon
5 # doesn't use much resources.
my-medium.cnf:
1 # Example MySQL config file for medium systems.
2 #
3 # This is for a system with little memory (32M - 64M) where MySQL plays
4 # an important part, or systems up to 128M where MySQL is used together with
5 # other programs (such as a web server)
my-large.cnf:
1 # Example MySQL config file for large systems.
2 #
3 # This is for a large system with memory = 512M where the system runs mainly
4 # MySQL.
my-huge.cnf:
1 # Example MySQL config file for very large systems.
2 #
3 # This is for a large system with memory of 1G-2G where the system runs mainly
4 # MySQL.
my-innodb-heavy-4G.cnf:
1 #BEGIN CONFIG INFO
2 #DESCR: 4GB RAM, InnoDB only, ACID, few connections, heavy queries
3 #TYPE: SYSTEM
4 #END CONFIG INFO
5
6 #
7 # This is a MySQL example config file for systems with 4GB of memory
8 # running mostly MySQL using InnoDB only tables and performing complex
9 # queries with few connections.
選擇一個合适你所在環境的腳本,我選的是meidum :sudo cp my-meidum.cnf /etc/my.cnf
打開找到一下指令
[ mysql]
default-character-set=latin1
[mysqld]
default-character-set=latin1
将latin1改為 utf8 (如果沒有就自己加上);
更改預設字元集後,還得把phpmyadmin的連接配接校對方式全部改成你所選擇的字元集,這裡是 utf8_general_ci。
注意:不但資料庫的連接配接校對方式要改,表單的連接配接校對方式也得改
好了,現在通過phpmyadmin 錄入的資料都可以正常顯示了。但是php做的頁面還會顯示亂碼。得在連接配接資料庫的代碼中添加指定字元集,你所選擇的資料庫的字元集是什麼,你就在後面加上該種字元集就行了。例如
<?php
$conn = mysql_connect("localhost","root","");
mysql_query("set names 'utf8'");//這就是指定資料庫字元集,一般放在連接配接資料庫後面就系了
mysql_select_db("test");
?>
ok,亂碼問題解決了。