問題描述
我使用 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模板網!