Home > php教程 > php手册 > 解决PHP存取MySQL 4.1乱码问题

解决PHP存取MySQL 4.1乱码问题

WBOY
Release: 2016-06-21 09:15:40
Original
1551 people have browsed it

mysql|解决|问题

从MySQL 4.1开始引入的多语言支持确实很棒,而且一些特性已经超过了其他的数据库系统。不过我在测试过程中发现使用适用于MySQL 4.1之前的PHP语句操作MySQL数据库会造成乱码,即使是设置过了表字符集也是如此。我读了一下新的MySQL在线手册中第十章"Character Set Support"后终于找到了解决方法并测试通过。

MySQL 4.1的字符集支持(Character Set Support)有两个方面:字符集(Character set)和排序方式(Collation)。对于字符集的支持细化到四个层次: 服务器(server),数据库(database),数据表(table)和连接(connection)。

查看系统的字符集和排序方式的设定可以通过下面的两条命令:

mysql> SHOW VARIABLES LIKE 'character_set_%';
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
7 rows in set (0.00 sec)

mysql> SHOW VARIABLES LIKE 'collation_%';
+----------------------+-------------------+
| Variable_name | Value |
+----------------------+-------------------+
| collation_connection | latin1_swedish_ci |
| collation_database | latin1_swedish_ci |
| collation_server | latin1_swedish_ci |
+----------------------+-------------------+
3 rows in set (0.00 sec)


上面列出的值就是系统的默认值。(很奇怪系统怎么默认是latin1的瑞典语排序方式)...

当我们按照原来的方式通过PHP存取MySQL数据库时,就算设置了表的默认字符集为utf8并且通过UTF-8编码发送查询,你会发现存入数据库的仍然是乱码。问题就出在这个connection连接层上。解决方法是在发送查询前执行一下下面这句:

SET NAMES 'utf8';

它相当于下面的三句指令:
SET character_set_client = utf8;
SET character_set_results = utf8;
SET character_set_connection = utf8;

再试试看,正常了吧?^_^ Enjoy!



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template