pdo 写入到数据库的内容为中文的时候写入乱码
问题描述
<?phpif(empty($_POST['phone'])){ //这个为中文的时候 数据库乱码return_json(1,'手机号不能为空'); }if(empty($_POST['pwd'])){return_json(2,'密码不能为空');}$phone = find('php_user','*','phone='.$_POST['phone']);if($phone){return_json(3,'手机号已存在');}$arr = array('phone' => $_POST['phone'],'pwd' => md5($_POST['pwd']),'add_time' => time(),'nickname' => isset($_POST['nickname']) ? $_POST['nickname'] : $_POST['phone'],'sex' => isset($_POST['sex']) ? $_POST['sex'] : 0,'avatar' => isset($_POST['avatar']) ? $_POST['avatar'] : '');$add = insert('php_user',$arr);return_json(0,'注册成功');function connect(){ $db = array('charset' => 'utf8','port' => 3306, 'type' => 'mysql','host' => '127.0.0.1', 'user' => 'hao2', 'pass' => 'hao3', 'name' => 'hao1' ); $dsn = "{$db['type']}:host={$db['host']}; dbname={$db['name']}; charset={$db['charset']}; port={$db['port']}" try {//实例化PDO类,创建PDO对象$pdo = new PDO($dsn,$db['user'],$db['pass']); } catch (PDOException $e) {die('数据库错误:'.$e->getMessage()); } return $pdo;}function insert($table,$data=[]){ //连接pdo $pdo = connect(); //创建SQL语句 $sql = "INSERT INTO {$table} SET "; //组装插入语句 if(is_array($data)){foreach ($data as $k=>$v) { $sql .= $k.'="'.$v.'", ';} }else{return false; } //去掉尾部逗号,并添加分号结束 $sql = rtrim(trim($sql),',').';'; //创建PDO预处理对象 $stmt = $pdo->prepare($sql); //执行新增操作 if($stmt->execute()){if($stmt->rowCount()>0){ return true;} } else {return false; }}
问题解答
回答1:看看你数据库的编码方式和你php中的编码方式