php pdo mysql utf8_PHP:使用PDO从MySQL数据库输出utf8时出现问题

bd96500e110b49cbb3cd949968f18be7.png

$dbo = new PDO("mysql:host=localhost;dbname=database", "databaseuser",

"databasepassword", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

$dbo -> exec("set character_set_client='utf8'");

$dbo -> exec("set character_set_results='utf8'");

$dbo -> exec("set collation_connection='utf8_general_ci'");

$prepSnapRetrieve = $dbo->prepare(

"SELECT * FROM znc_log WHERE `nick` LIKE :u AND `tstamp` BETWEEN :t1 AND :t2"

);

$prepSnapRetrieve->execute(array(':u' => str_replace("|osu","", $_GET['u']),

':t1' => $_GET['sns'], ':t2' => $_GET['sne']));

$snapshotListing = $prepSnapRetrieve->fetchAll();

echo("Snapshot of ".$_GET['u']. "'s chat on ".strftime("%e/%m/%g",$_GET['sne']));

echo("
");

foreach($snapshotListing as $chat) {

echo "" . " " . "[" . strftime("%H:%M:%S", $chat['tstamp']) . "]" .

" " . " >" . $chat['channel'] . "< " . "(" .

htmlspecialchars($chat['nick']).") ".htmlspecialchars($chat['message']);

echo("
");

}

This snippet is code is supposed to parse and output IRC data which has been stored in UTF-8 - but upon echoing, any unicode content simply appears as:

??????

I have reviewed several questions and included several purported fixes, but nothing appears to work. Another script using the same database echoes UTF-8 content perfectly, but it is using the standard MySQL implementation of PHP, and not PDO. What am I doing wrong?

解决方案

There are multiple points of failure, when working with UTF8:

make sure the table is utf8

Use SQL-Command Show Variables; to check the MySQL character settings for the table.

inserted data is utf8

You might try tools like phpMyAdminer or Adminer to check, if the

data is inserted correctly. Try to insert data via the tool manually.

When inserting via script, do not use basic string functions. Always use their mbstring

alternatives. Set mb_internal_encoding( 'UTF-8' ); to let PHP handle UTF-8 internally.

fetched data is utf8

I would only use $pdo->exec("SET NAMES utf8"); and drop the rest. Because

SET NAMES x is equivalent to

SET character_set_client = x;

SET character_set_results = x;

SET character_set_connection = x;

displayed data is utf8

If this is displayed in an html page, do not forget to set the meta tag or header

"Content-Type: text/html; charset=utf-8".

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值