gpt4 book ai didi

php - 如何在PDO中设置字符集

转载 作者:行者123 更新时间:2023-11-29 12:03:56 26 4
gpt4 key购买 nike

我在 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,但它在数据库中存储为céréales。有人知道如何在pdo中将字符集设置为utf8吗?

最佳答案

您已在连接字符串中设置 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));

关于php - 如何在PDO中设置字符集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31891455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com