Reputation: 117
i've some issue with setting character set in pdo. Below is my connection code :-
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();
}
}
I am inserting french character as céréales
but it is storing as céréales
in DB. Anyone know how to set character set to utf8 in pdo?
Upvotes: 0
Views: 5624
Reputation: 6064
You are already setting the utf8 charset in the connection string. You don't have to send another query like "SET NAMES 'uft8'".
You just have to make sure that:
Mysql table and field are utf8 (like uft8_general_ci)
Input data is utf-8
The array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
is also useless. This is the faster way to set all your parameters:
$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));
Upvotes: 1