PDO UTF-8编码问题? [英] PDO UTF-8 encoding issue?

查看:68
本文介绍了PDO UTF-8编码问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i am using PDO for connecting to MYSQL database

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

all tables in database have utf8_unicode_ci Collation

这是我的连接代码:

<?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");
}
?>

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

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

推荐答案

此:

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

完全没有意义.参见 http://php.net/manual/en/ref.pdo-mysql.php . MYSQL_ATTR_INIT_COMMAND在连接建立后立即执行,不会再执行.如果在已经完全创建的PDO对象上进行设置,则为时已晚,并且永远不会执行.您需要将其传递给构造函数:

is entirely pointless. See http://php.net/manual/en/ref.pdo-mysql.php. The MYSQL_ATTR_INIT_COMMAND is 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:

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

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

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

这篇关于PDO UTF-8编码问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆