我使用 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");
}
?>
在本地主机中,我对编码没有问题,但是当我将源上传到主机时,我看到的是 ?????? 而不是字符?
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 编码问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!