set_charset and PDO?


I have (almost) decided to change from Mysqli to PDO. But have run into one problem: charset.

In Mysqli I used


(in the db connection) to be sure that swedish letter was saved properly in the mysql database.

But using PDO to connect something is wrong. And I can’t find any similar to use with PDO.

The php-page have charset utf-8 in the header, Mysql is set to UTF-8 Unicode_ci (localhost), the db and tables have collation set to utf8_unicode_ci.

This is a common issue for me everytime :frowning: But how to solve it with PDO. Mysqli and set_charset(‘utf8’) worked like a dream :slight_smile:

Regards, Magnus

Try putting this in the PDO instantiation string:


Inside the DSN string. I’m not sure if it’ll work, but you can give it a try.

This is a common issue for me everytime

I’ve never experienced such a problem, and I’m using PDO all the time. Is there actually a charset problem or are you taking precautions?

I think so :confused:

Using PDO connection to insert into db gives wrong character (checked with phpmyadmin - served as UTF-8). Using Mysqli and set_charset works fine (had the same problem first before added the set_charset).

Well, I tried your idea. Added it at the end of the DNS string. But no, same problem :headbang:

Regards, Magnus


More: Connection Character Sets and Collations.

Gulp, lets hope there is an easy way round this.

Kore Nordman in his faq says:

You can also set the connection charset only for one connection, by sending the following query before you send data to the database server:


Thanks everybody :slight_smile: You are truly experts.

I added this line

$pdoConnectLink->query('SET NAMES utf8');

in the method where I create the PDO connection. Ended up like this:

$pdoConnectLink = new PDO($this->_dbstring, $this->_username, $this->_password);
$pdoConnectLink->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdoConnectLink->query('SET NAMES utf8');
return $pdoConnectLink;


Your sincerely Magnus

I was having the same issue. Thanks for the solution. :slight_smile:

Btw, if anyone have a class, this could be usefull:

$db = new PDO('mysql:host=localhost; port=3306; dbname=something', 'root', '', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

or this:

private $arrayopt;
$this->arrayopt= array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
parent::__construct($this->dsn, $this->username, $this->password, $this->arrayopt);