解决PHP写MySQL数据乱码问题

在创建数据要设定整个数据或数据字段为utf8编码:

只设定单个字段为utf8编码的实例:
[sql highlight_lines=”4″]
CREATE TABLE IF NOT EXISTS `mytweets` (
`id` bigint(20) NOT NULL,
`time` datetime NOT NULL,
`text` varchar(200) CHARACTER SET utf8 NOT NULL,
`type` varchar(20) NOT NULL,
`screen_name` varchar(50) DEFAULT NULL,
`status_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
);[/sql]

设定整个表所有字符型字段为utf8的实例:
[sql highlight_lines=”9″]
CREATE TABLE IF NOT EXISTS `mytweets` (
`id` bigint(20) NOT NULL,
`time` datetime NOT NULL,
`text` varchar(200) NOT NULL,
`type` varchar(20) NOT NULL,
`screen_name` varchar(50) DEFAULT NULL,
`status_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;[/sql]

PHP里把.php文件的编码设为utf-8,然后在打开数据库调用下面这一行设定对应的编码为utf-8:
[php]mysql_query(‘SET NAMES utf8 COLLATE utf8_general_ci’, $dbConn);[/php]

我原来写成下面这一行结果写到数据库还是乱码,这是反样例子:
[php]mysql_query(‘SET NAMES utf-8’, $dbConn);[/php]

Tags: ,

Leave a Reply