Home > Article > Backend Development > PHP uses PDO to operate database garbled problem solutions and examples
This article mainly introduces the solution to the garbled code problem when PHP uses PDO to operate the database. It analyzes the implementation techniques of encoding settings and attribute settings to solve the garbled code problem. Friends in need can refer to the following
When using PDO When connecting to the database, sometimes it will appear that the Chinese characters saved in the database are garbled. If the file is in UTF-8 format, the solution is as follows:
(1) The instantiated object directly executes the query() method or exec() method:
<?php class DB { static public function getDB() { try { $_opts_values = array(PDO::ATTR_PERSISTENT=>true,PDO::ATTR_ERRMODE=>2); $_pdo = new PDO(DB_DSN, DB_NAME, DB_PASS, $_opts_values); } catch (PDOException $e) { exit('数据库连接错误!错误信息:'.$e->getMessage()); } $_pdo->query("SET NAMES utf8"); // $_pdo->exec('SET NAMES utf8'); //设置数据库编码,两种方法都可以 return $_pdo; } } ?>
(2) Add the MYSQL_ATTR_INIT_COMMAND attribute to the fourth parameter of the instantiated PDO:
<?php class DB { static public function getDB() { try { $_opts_values = array(PDO::ATTR_PERSISTENT=>true,PDO::ATTR_ERRMODE=>2,PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES utf8'); $_pdo = new PDO(DB_DSN, DB_NAME, DB_PASS, $_opts_values); } catch (PDOException $e) { exit('数据库连接错误!错误信息:'.$e->getMessage()); } return $_pdo; } } ?>
Summary: The above is this The entire content of this article is hoped to be helpful to everyone's study.
Related recommendations:
PHP regular expression basics entry
php UEditor Baidu editor Sharing how to install and use the server
Swoole extension installation method and detailed tutorial in PHP
##
The above is the detailed content of PHP uses PDO to operate database garbled problem solutions and examples. For more information, please follow other related articles on the PHP Chinese website!