PDO charset从iso-8859-2到UTF8

时间:2012-06-02 13:01:49

标签: php mysql utf-8 character-encoding pdo

我在MySQL DB中有一个字段:

description     text    utf8_general_ci

我使用CURL废弃网站iso-8859-2并尝试将值插入utf8_general_ci字段。一切都还好,但我失去了角色,即。 ęąśćż等你能帮助我吗?

我通过PDO连接到数据库:

 $pdo = new PDO('mysql:host=localhost;dbname=xx;charset=utf8', 'xxx', 'xxx');
 $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

比我准备我的查询:

 $stmt1 = $pdo -> prepare('INSERT INTO `jos_djcf_items1` (`cat_id`, `user_id`, `name`, `description`, `intro_desc`, `date_start`, `display`, `published`, `contact`)    VALUES(
                                :cat_id,
                                :user_id,
                                :name,
                                :description,
                                :intro_desc,
                                :date_start,
                                :display,
                                :published,
                                :contact)'); // 1

我检查字符集:

$oferta[$j][0]= iconv("iso-8859-2","UTF-8",$nazwa);
$ary[] = "UTF-8";
$ary[] = "iso-8859-2";
$ary[] = "EUC-JP";
echo mb_detect_encoding($oferta[$j][0], $ary);
// it returns: UTF-8
$oferta[$j][1]=iconv("iso-8859-2","UTF-8",$krotkiOpis);
$oferta[$j][2]=iconv("iso-8859-2","UTF-8",$opis);
$oferta[$j][3]=iconv("iso-8859-2","UTF-8",$kontakt);
$oferta[$j][4]=rand(3,40);

比绑定值并执行查询

$count += $stmt1 -> execute(); 

1 个答案:

答案 0 :(得分:3)

在PHP 5.3.6之前,您应该如何设置连接字符集:

$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

$pdo = new PDO('mysql:host=localhost;dbname=xx', 'xxx', 'xxx', $options);

请注意,编码必须与ASCII兼容。