问题描述
我在 PHP 中使用带有 MySQL 数据库的 PDO 库,但是如果我插入任何以 UTF-8 编码的数据,如阿拉伯语单词,它会插入到数据库中,但作为 ?????????
.
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 ?????????
.
在我自己的框架中,在创建 PDO 连接后,我发送了两个查询 - SET NAMES utf8
和 SET CHARACTER SET utf8
.还是不行.
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.
示例:
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'));
解决方法:数据插入数据库前使用json_encode
函数进行转换,获取后使用json_decode
进行解码.我现在就是这样做的.
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.
推荐答案
使用:
Use:
$pdo = new PDO(
'mysql:host=hostname;dbname=defaultDbName',
'username',
'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
);
它在 PDO 连接上强制使用 UTF-8.它对我有用.
It forces UTF-8 on the PDO connection. It worked for me.
这篇关于PDO + MySQL 和损坏的 UTF-8 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!