php 写入数据到MySQL以及从MySQL获取数据,页面出现乱码的解决方法
现象如标题。
解决思路:
1确定数据库charset是否是utf-8
a. charset不是utf-8
1, 更改数据库charset为utf-8
ALTER DATABASE db_name DEFAULT CHARACTER SET utf8;
2, 更改表格charset为utf-8
ALTER TABLE tbl_name DEFAULT CHARACTER SET utf8;
3, 更改表格列表为utf-8
ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8;
b.charset是utf-8
1,在php中添加
header('charset=utf-8');
2,在连接到数据库后,添加如下代码,写入数据和获取数据的地方均要添加
mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $con);