建表时先加上default charset=utf8;
插入中文数据之前(Mysql命令提示符下)是用set names gb2312;
在php页面中设置是mysql_query('SET NAMES UTF8');
在php页面(已设定为utf8后)中插入中文数据不会出现乱码,应该插入数据库的时候就是以utf8字符集插入中文数据的故不会出现问题!
在php页面前面不要忘了加上header('content-type;text/html;charset=utf-8');
大家在MySQL命令提示符下想查看数据,中文数据有可能是如下 '?????'
所以大家想查看到正确的中文要与插入中文数据一样使用set names gb2312;
例子:
CREATE DATABASE mydb;
USE mydb5;
CREATE TABLE news
(
)default charset=utf8;
set names gb2312;
INSERT INTO news VALUES(null, '新闻1', '111111', now());
INSERT INTO news VALUES(null, '新闻2', '222222', now());
INSERT INTO news VALUES(null, '新闻3', '333333', now());
INSERT INTO news VALUES(null, '新闻4', '444444', now());
INSERT INTO news VALUES(null, '新闻5', '555555', now());
Microsoft Windows XP [版本 5.1.2600]
(C) 版权所有 1985-2001 Microsoft Corp.
C:\Documents and Settings\YSDH.YSDH-0>cd \
C:\>mysql -h localhost -uroot -p
Enter password: ******
Welcome to the MySQL monitor.
Your MySQL connection id is 6 to server version: 5.0.22-community-nt-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use mydb;
Database changed
mysql> INSERT INTO vote VALUES(null,'你是从哪里了解到本站的?',1,default);
Query OK, 1 row affected (0.00 sec)
mysql> set names utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO vote VALUES(null,'你是从哪里了解到本站的?',1,default);
ERROR 1406 (22001): Data too long for column 'vote_title' at row 1 (varchar(100) 还不够?)
mysql> describe vote;
+------------+--------------+------+-----+---------+----------------+
| Field
+------------+--------------+------+-----+---------+----------------+
| vote_id
| vote_title | varchar(100) | NO