关于如何解决php 用pdo 传中文数据给mysql乱码的问题,我在网上搜了好久,总结了一下,不足的地方请大家见谅。
linux下文件的存储格式本身就是utf8格式 这个我们可以不用变化。
html页面
我们要在<head>加上这句代码
<meta http-equiv="Content-Type" content="text/html:charset=utf-8">
在php 页面
在<?php 后面加上
header("Content-Type:text/html;charset=utf-8");
建立数据库的时候,比如叫做test
create table test
(
name varchar(200) not null
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
后面的ENGINE=InnoDB DEFAULT CHARSET=utf8 是为了设置数据库编码格式为utf8格式
建立php与mysql链接的时候
<?php
$dbms='mysql';
$host='localhost';
$dbName='BBS';
$user='root';
$pass='784863455';
$dsn="$dbms:host=$host;dbname=$dbName";
try
{
$pdo=new pdo($dsn,$user,$pass,array(PDO::MYSQL_ATTR_INIT_COMMAND=>"set names utf8"));
}catch(PDOException $e)
{
die ("connect error !".$e->getMessage()."</br>");
}
红色那部分保证了传送过去的数据为utf8模式
然后就可以愉快的传输中文啦