PHP uses PDO to operate database garbled characters. Solution

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.