Home > Backend Development > PHP Tutorial > PHP uses PDO to operate the database garbled problem solution_php skills

PHP uses PDO to operate the database garbled problem solution_php skills

WBOY
Release: 2016-05-16 19:54:32
Original
1232 people have browsed it

The example in this article describes how to solve the garbled problem of PHP using 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:

<&#63;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;
    }
  }
&#63;>

Copy after login

(2) Add the MYSQL_ATTR_INIT_COMMAND attribute to the fourth parameter of the instantiated PDO:

<&#63;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;
    }
  }
&#63;>

Copy after login

Note: The above methods have been tested.

Readers who are interested in more PHP-related content can check out the special topics of this site: "Summary of PHP database operation skills based on pdo", "Summary of PHP operations and operator usage" , "Summary of PHP network programming skills", "Introduction tutorial on basic PHP syntax", "Summary of PHP operating office document skills (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.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template