PDO charset problems

These are the problems of the world before PHP6. Soon to be forgotten.
I was working in my application with different charsets, like slavic (cyrillic), japanese or arabic and in the database all was peachy and the localized information was stored correctly under utf8_unicode_ci encoding. The problem was that the php received and printed wrong information, like question marks or squares or strange chars, and this usually happens when the headers are not set properly which was not the case.

I am using PDO as the abstraction layer in this project, and it appears that you have to specificly state your pdo connection what type of encoding you want for transfer.

$db->query('SET NAMES UTF8');

For mysqli

$mysqli->query("SET NAMES 'utf8'");

This simple line in the connection part solve it all. Actually this is not even a PDO thing, is a mySQL thing; in this case we instruct the server and the client what encoding to use in the communication.

This is more a workaround, because the communication should be done depending on the _default-character-set_ variable from mysql ini file. There are several bugs related with this problem in php and mysql bug zoo.


About this entry