Friday, 28 April 2017

php - PDO + MySQL and broken UTF-8 encoding



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




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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...