我在pdo中设置字符集时遇到了一些问题。以下是我的连接代码: -
private function Connect()
{
$this->settings = parse_ini_file("settings.ini.php");
//$dsn = 'mysql:dbname='.$this->settings["dbname"].';host='.$this->settings["host"].'';
$dsn = 'mysql:dbname=' . $this->settings["dbname"] . ';host=' . $this->settings["host"] .';charset=utf8'. ';connect_timeout=15';
try
{
# Read settings from INI file, set UTF8
$this->pdo = new PDO($dsn, $this->settings["user"], $this->settings["password"], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
# We can now log any exceptions on Fatal error.
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
# Disable emulation of prepared statements, use REAL prepared statements instead.
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
# Connection succeeded, set the boolean to true.
$this->bConnected = true;
}
catch (PDOException $e)
{
# Write into log
echo $this->ExceptionLog($e->getMessage());
die();
}
}
我将法语字符插入céréales
,但它在DB中存储为céréales
。有人知道如何在pdo中将字符集设置为utf8吗?
答案 0 :(得分:1)
您已在连接字符串中设置utf8字符集。您不必发送其他查询,例如" SET NAMES' uft8'"。
你必须确保:
Mysql表和字段是utf8(如uft8_general_ci)
输入数据为utf-8
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
也没用。这是设置所有参数的更快捷方式:
$this->pdo = new PDO('mysql:host='.$this->settings["host"].';dbname='.$this->settings["dbname"].';
charset=utf8;connect_timeout=15', $this->settings["user"], $this->settings["password"],
array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));