This article describes how to solve the garbled problem of using PDO to operate databases in PHP. The example analyzes the implementation skills of encoding and attribute settings to solve the garbled problem, for more information about how to use PDO to operate databases in PHP, see the example below. We will share this with you for your reference. The details are as follows:
When you use PDO to connect to and operate the database, the Chinese characters stored in the database are garbled. In UTF-8 format, the solution is as follows:
(1) The instantiated object directly executes the query () method or the 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 ('database connection error! Error message :'. $ e-> getMessage (); }$ _ pdo-> query ("set names utf8"); // $ _ pdo-> exec ('set NAMES utf8 '); // Set the database encoding. you can return $ _ pdo in either of the two methods. }}?>
(2) add the MYSQL_ATTR_INIT_COMMAND attribute in the fourth parameter of PDO instantiation:
<? 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 ('database connection error! Error message: '. $ e-> getMessage () ;}return $ _ pdo ;}}?>
Note: The above methods have been tested.