PDO + MySQL 和损坏的 UTF-8 编码 [英] PDO + MySQL and broken UTF-8 encoding

查看:26
本文介绍了PDO + MySQL 和损坏的 UTF-8 编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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 utf8SET 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.

推荐答案

警告:此答案适用于 PHP 5.3.5 及更低版本.请勿将其用于 PHP 5.3.6 版(2011 年 3 月发布)或更高版本.

Warning: This answer applies to PHP 5.3.5 and lower. Do not use it for PHP version 5.3.6 (released in March 2011) or later.

Palec 的回答进行比较这里.


使用:


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 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆