This article describes the example of the solution to the garbled code problem when PHP uses PDO to operate the database. Share it with everyone for your reference, the details are as follows:
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) 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; } } ?>
Note: The above methods have been tested.
Readers who are interested in more PHP-related content can check out the special topics on this site: "Summary of PHP database operation skills based on pdo", "Summary of PHP operations and operator usage", "Summary of PHP network programming skills", "PHP basic Grammar introductory tutorial", "php office document operation skills summary (including word, excel, access, ppt)", "php date and time usage summary", "php object-oriented programming introductory tutorial", "php string (string) Usage summary", "php mysql database operation introductory tutorial" and "php common database operation skills summary"
I hope this article will be helpful to everyone in PHP programming.