Brake6
February 19, 2009, 3:54pm
1
Hello
I have (almost) decided to change from Mysqli to PDO. But have run into one problem: charset.
In Mysqli I used
set_charset('utf8')
(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 But how to solve it with PDO. Mysqli and set_charset(‘utf8’) worked like a dream
Regards, Magnus
Try putting this in the PDO instantiation string:
charset=UTF-8
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?
Brake6
February 19, 2009, 5:02pm
3
I think so
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
SET NAMES utf8;
SET CHARACTER SET utf8;
More: Connection Character Sets and Collations .
Cups
February 19, 2009, 5:14pm
5
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:
SET NAMES utf8
Brake6
February 19, 2009, 5:57pm
6
Thanks everybody 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
oikram
April 6, 2009, 10:10am
7
I was having the same issue. Thanks for the solution.
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);
Regards,
Márcio