日期:2014-05-16  浏览次数:20755 次

php往mysql写数据,中文乱码问题.

最近做一个聊天的项目,用了jaxl来让xmpp server转发消息给web server.然后webserver会保存消息到本地数据库(mysql).

发现mysql中中文为乱码.解决思路:

1.首先检查了自己生成数据库(和table)的脚本中有没有做utf8的设置(通过).

2.yii框架的配置文件中,关于数据库配置有没有 'charset' => 'utf8', (通过).

3.查看mysql 数据库编码方式:

mysql> show variables like 'character_set_%';
+--------------------------+----------------------------+
| Variable_name??????????? | Value????????????????????? |
+--------------------------+----------------------------+
| character_set_client???? | latin1???????????????????? |
| character_set_connection | latin1???????????????????? |
| character_set_database?? | utf8?????????????????????? |
| character_set_filesystem | binary???????????????????? |
| character_set_results??? | latin1???????????????????? |
| character_set_server???? | utf8?????????????????????? |
| character_set_system???? | utf8?????????????????????? |
| character_sets_dir?????? | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
于是乎将其改为:

+--------------------------+----------------------------+
| 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/ |
+--------------------------+----------------------------+
问题依然存在,这时我想可能是数据写入的时候,就将乱码写入了.也就是说是php(jaxl是php写的)往mysql写数据时有问题.

4.在jaxl中php往jaxl写数据的代码前加入: mysql_query("SET NAMES 'utf8'");

这样,便将php默认字符集设置为utf8(一定要注意,这里是utf8,而不是utf-8).

好的,问题解决...

?

补充:

最近两天又研究下了这个问题,做一个补充.

上面提到的在每次读写数据时添加mysql_query("SET NAMES 'utf8'");

的方法不是很理想,因为我不想每次都添加.也有人提供了一个好办法,用OOP来编写php程序,将数据库读写查询写成一个类,这样就方便多了.

其实,这里还有一个办法可以更加优雅的解决这个问题:修改mysql的配置文件my.cnf

(ubuntu下,my.cnf文件的位置:/etc/mysql/my.cnf)

我们只需要在[mysqld] 下添加

init-connect='SET NAMES utf8'

?

即可.

?

?

?

--------------------------------------

这儿有人提供了一个utf8和my.cnf的配置,非常有用

from:http://notes.timeghost.net/2008/10/utf-8-and-mycnf.html

?

[mysqld]
default-character-set=utf8
default-collation=utf8_general_ci
character-set-server=utf8
collation-server=utf8_general_ci
init-connect='SET NAMES utf8'
 
[client]
default-character-set=utf8

?

?

?