PDO + MySQL and broken UTF-8 encoding

Jason4Ever picture Jason4Ever · Dec 18, 2010 · Viewed 65.2k times · Source

I use the PDO library with a MySQL database in PHP, but if I insert any data encoded in UTF-8, like Arabic words, it’s inserted into the database, but as ?????????.

In my own framework, after I create the PDO connection, I send two queries – SET NAMES utf8 and SET CHARACTER SET utf8. It still doesn’t work.

Example:

loadclass('PDO', array(
    sprintf(
        'mysql:host=%s;port=%s;dbname=%s',
        confitem('database', 'host'),
        confitem('database', 'port'),
        confitem('database', 'name')
    ),
    confitem('database', 'username'),
    confitem('database', 'password'),
    array('PDO::ATTR_PERSISTENT' => confitem('database', 'pconnect'))
));
$this->query('SET NAMES ' . confitem('database', 'charset'));
$this->query('SET CHARACTER SET ' . confitem('database', 'charset'));

Workaround: Use the json_encode function to convert data before inserting it to the database, and use json_decode to decode it after fetching. This is how I do it now.

Answer

shark555 picture shark555 · Aug 11, 2011

Use:

$pdo = new PDO( 
    'mysql:host=hostname;dbname=defaultDbName', 
    'username', 
    'password', 
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") 
); 

It forces UTF-8 on the PDO connection. It worked for me.