对于乱码这个问题php开发者几乎都会有碰到过,我们下面主要是介绍了php mysql数据库连接时乱码解决方法。

mysql数据库使用utf-8编码的问题

1.用phpmyadmin创建数据库和数据表

创建数据库的时候,请将“整理”设置为:“utf8_general_ci”或执行语句:

create database `dbname` default character set utf8 collate utf8_general_ci;

创建数据表的时候:如果是该字段是存放中文的话,则需要将“整理”设置为:“utf8_general_ci”,如果该字段是存放英文或数字的话,默认就可以了。

相应的sql语句,例如:

create table `test` (

`id` int not null ,

`name` varchar( 10 ) character set utf8 collate utf8_general_ci not null ,

primary key ( `id` )

) engine = myisam ;

2.用php读写数据库

在连接数据库之后

$connection = mysqli_connect($host_name, $host_user, $host_pass);

加入:

mysqli_query("set character set 'utf8'");//读库

mysqli_query("set names 'utf8'");//写库

就可以正常的读写mysql数据库了。

用的appserv-win32-2.5.10做的环境,装这个包的时候用默认的utf8编码。

在写数据库连接文件时,写成:

$conn = mysqli_connect("$host","$user","$password");

mysqli_query("set names 'utf8'");

mysqli_select_db("$database",$conn);

然后在做页面时,注意这句:

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

这样不管输入数据库的中文,还是页面显示,就都正常了。

在dw cs4版里,默认生成的也是utf8页面。

同样的,如果一开始写数据库连接文件时写成:

mysqli_query("set names 'gbk'");

那页面也要相应变成:

<meta http-equiv="content-type" content="text/html; charset=gb2312" />

以上就是php写入数据库乱码的详细内容,感谢大家的阅读和对www.887551.com的支持。