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

问题描述

我在PHP中使用带有MySQL数据库的PDO库,但是如果我插入任何以UTF-8编码的数据,例如阿拉伯语,它会插入到数据库中,但是在我自己的框架中,在我创建PDO连接后,我发送两个查询 - SET NAMES

utf8 SET CHARACTER SET utf8 。它仍然不起作用。



示例:

  loadclass 'PDO',array(
sprintf(
'mysql:host =%s; port =%s; dbname =%s',
confitem('database','host'
confitem('database','port'),
confitem('database','name')
),
confitem
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
在提取后对其进行解码。

解决方案

这可能是在几年前解决,但是为了后代: p>

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

它强制在pdo连接上使用UTF-8。为我工作。


I use the PDO library with 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 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.

解决方案

It has been probably solved years ago, but for future generations' sake:

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

It forces UTF-8 on pdo connection. Worked for me.

这篇关于PDO + MySQL和破坏的UTF-8编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:47