Home > Backend Development > PHP Tutorial > PHP uses PDO to operate database garbled problem solutions and examples

PHP uses PDO to operate database garbled problem solutions and examples

墨辰丷
Release: 2023-03-29 16:18:01
Original
1452 people have browsed it

This article mainly introduces the solution to the garbled code problem when PHP uses PDO to operate the database. It analyzes the implementation techniques of encoding settings and attribute settings to solve the garbled code problem. Friends in need can refer to the following

When using PDO When connecting to the database, sometimes it will appear that 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;
    }
  }
?>
Copy after login

(2) Add the MYSQL_ATTR_INIT_COMMAND attribute to the fourth parameter of the instantiated 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;
    }
  }
?>
Copy after login

Summary: The above is this The entire content of this article is hoped to be helpful to everyone's study.

Related recommendations:

PHP regular expression basics entry

php UEditor Baidu editor Sharing how to install and use the server

Swoole extension installation method and detailed tutorial in PHP

##

The above is the detailed content of PHP uses PDO to operate database garbled problem solutions and examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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