php PDO UTF-8 编码问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18496557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:39:13  来源:igfitidea点击:

PDO UTF-8 encoding issue?

phpmysqlutf-8pdo

提问by Mohammad Masoudian

i am using PDO for connecting to MYSQL database

我正在使用 PDO 连接到 MYSQL 数据库

all tables in database have utf8_unicode_ciCollation

数据库中的所有表都有utf8_unicode_ci排序规则

here is my connection code :

这是我的连接代码:

<?php
$mysql_username = "root";
$mysql_password = "";
$mysql_host = "localhost";
$mysql_database = "cms";

try
{
    //connect
    global $db;
    $db = new PDO('mysql:dbname=' . $mysql_database . ';host=' . $mysql_host . ';charset=utf8;', $mysql_username, $mysql_password);
    $db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex)
{
    die("Unable Connect To DataBase");
}
?>

in localhost i have no problem with encoding but when i uploaded the source to a host i see ??????instead of characters?

在本地主机中,我对编码没有问题,但是当我将源上传到主机时,我看到?????? 而不是字符?

回答by deceze

This:

这个:

$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');

is entirely pointless. See http://php.net/manual/en/ref.pdo-mysql.php. The MYSQL_ATTR_INIT_COMMANDis executed right after the connection is established, no later. If you set this on an already fully created PDO object, it's too late and it never executes. You need to pass it to the constructor:

完全没有意义。请参阅http://php.net/manual/en/ref.pdo-mysql.php。在MYSQL_ATTR_INIT_COMMAND建立连接后,最迟不执行的权利。如果你在一个已经完全创建的 PDO 对象上设置它,那就太晚了,它永远不会执行。您需要将其传递给构造函数:

new PDO(..., ..., ..., array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'))

Alternatively, if your PHP version supports it, add charset=utf8to the DSN.

或者,如果您的 PHP 版本支持它,请添加charset=utf8到 DSN。