exec('SET NAMES utf8');"; 2. Add the "MYSQL_ATTR_INIT_COMMAND" attribute to the fourth parameter of instantiated PDO."/> exec('SET NAMES utf8');"; 2. Add the "MYSQL_ATTR_INIT_COMMAND" attribute to the fourth parameter of instantiated PDO.">
Home > Article > Backend Development > How to set encoding in php pdo
php pdo setting encoding method: 1. Set the database encoding through "$_pdo->exec('SET NAMES utf8');"; 2. Add "MYSQL_ATTR_INIT_COMMAND" to the fourth parameter of instantiated PDO "Attributes.
The operating environment of this article: windows7 system, php5.2.4 version, DELL G3 computer
Solution to the garbled problem of PHP using PDO to operate the database, php pdo setting encoding:
When using PDO connection to operate the database, sometimes it will appear: 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) In the instance Add the MYSQL_ATTR_INIT_COMMAND attribute to the fourth parameter of 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; } } ?>
Note: The above methods have been tested.
[Recommended learning: PHP video tutorial]
The above is the detailed content of How to set encoding in php pdo. For more information, please follow other related articles on the PHP Chinese website!