[花果山水帘洞] Getting '??' when reading Chinese characters from MYSQL with PHP(PDO)

如果遇到 PHP(PDO) 从 mysql 读取中文不正常该怎么办?

Getting '??' when reading Chinese characters from MYSQL with PHP(PDO)

2016-05-11 / vc12345679

Getting '??' when reading Chinese characters from MYSQL with PHP(PDO)

Problem

Everything worked well when I tested it on my laptop. Once I migrated it to the VPS this afternoon, something went wrong.

  • Chinese characters originally in *.php and *.html were normally displayed
  • Chinese characters in *.php read from MYSQL by PDO displayed as '??'

Checking

First thaught came up to me was the ENCODING. So I checked all the encoding settings.

  • Database
  • MYSQL had been set to use utf8-general-ci, so did the tables and the fields. Chinese characters displayed well in phpMyAdmin.
  • Web Server
  • Nginx had been set to use UTF-8 as default encoding.
  • All *.php and *.html files had been encoded with UTF-8.
  • Charset had been set to UTF-8 in all meta fileds of HTML headers.
  • Client
  • Browers had detected the encoding correctly.

Solution

Still the problem occured. Then it must be something wrong when PDO reading from MYSQL. I tried to force PDO to read using UTF-8.

$db = new PDO(""mysql:host=HOSTNAME;dbname=DATABASE"", 'USERNAME', 'PASSWORD' ,array (PDO::MYSQL_ATTR_INIT_COMMAND => ""SET NAMES 'UTF8';""));

Guess what? It solved.

PHP(PDO) 从 MYSQL 读取中文显示问号??

问题现象

在本机开发调试时,显示都是正常的;但下午我把网站上传到了 VPS,中文显示出问题了。

  • *.php*.html 里自带的中文字符串显示正常
  • *.php 中 PDO 从 MYSQL 读取的中文显示成了问号 ‘??’

检查

我的第一反应是编码问题,因此我检查了所有相关的编码设置。

  • 数据库
  • MYSQL 表格 和 字段 均已经设置为使用utf8-general-ci;并且在 phpMyAdmin 里中文显示也是正常的
  • 网页服务器
  • Nginx 已配置使用 UTF-8 作为默认编码
  • 所有的 *.php*.html 文件都使用的是 UTF-8 编码
  • 所有 HTML头 的 meta 部分均已声明使用 UTF-8 编码
  • 客户端
  • 浏览器也已正常识别编码

解决办法

但问题依然存在,我判断一定是 PDO 从 MYSQL 读取时发生了什么差错。我尝试强制 PDO 使用 UTF-8 编码。

$db = new PDO(""mysql:host=HOSTNAME;dbname=DATABASE"", 'USERNAME', 'PASSWORD' ,array (PDO::MYSQL_ATTR_INIT_COMMAND => ""SET NAMES 'UTF8';""));

结果,问题就这么解决了……"