PHP uses PDO to operate database garbled problem solution, pdo garbled. PHP uses PDO to solve the garbled problem of database operations. the example in this article describes how PHP uses pdo to solve the garbled problem of database operations. I will share it with you for your reference. the solution to the garbled problem of using PDO to operate databases in PHP is as follows:
This example describes how to solve the garbled problem of using PDO to operate databases in PHP. 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.