exec('SET NAMES utf8');"; 2. Add the "MYSQL_ATTR_INIT_COMMAND" attribute to the fourth parameter of instantiated PDO."/> exec('SET NAMES utf8');"; 2. Add the "MYSQL_ATTR_INIT_COMMAND" attribute to the fourth parameter of instantiated PDO.">

Home  >  Article  >  Backend Development  >  How to set encoding in php pdo

How to set encoding in php pdo

藏色散人
藏色散人Original
2021-05-25 09:08:482956browse

php pdo setting encoding method: 1. Set the database encoding through "$_pdo->exec('SET NAMES utf8');"; 2. Add "MYSQL_ATTR_INIT_COMMAND" to the fourth parameter of instantiated PDO "Attributes.

How to set encoding in php pdo

The operating environment of this article: windows7 system, php5.2.4 version, DELL G3 computer

Solution to the garbled problem of PHP using PDO to operate the database, php pdo setting encoding:

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(&#39;数据库连接错误!错误信息:&#39;.$e->getMessage());
      }
      $_pdo->query("SET NAMES utf8"); // $_pdo->exec(&#39;SET NAMES utf8&#39;); //设置数据库编码,两种方法都可以
      return $_pdo;
    }
  }
?>

(2) In the instance Add the MYSQL_ATTR_INIT_COMMAND attribute to the fourth parameter of 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=>&#39;SET NAMES utf8&#39;);
        $_pdo = new PDO(DB_DSN, DB_NAME, DB_PASS, $_opts_values);
      } catch (PDOException $e) {
        exit(&#39;数据库连接错误!错误信息:&#39;.$e->getMessage());
      }
      return $_pdo;
    }
  }
?>

Note: The above methods have been tested.

[Recommended learning: PHP video tutorial]

The above is the detailed content of How to set encoding in php pdo. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:How to install php 5.2.4Next article:How to install php 5.2.4