【问题标题】:Displaying Japanese characters from MySql database on PHP page在 PHP 页面上显示来自 MySql 数据库的日文字符
【发布时间】:2013-05-20 07:21:25
【问题描述】:

我正在尝试制作一个显示日文字符的页面。这些日文字符存储在我的数据库中。我已经完成了研究并尝试了许多给出的建议,但我的日文字符仍然作为问号返回。目前,这是我的代码的外观:

<?php


 $con=mysqli_connect("host", "user", "pw", "db");   
if (!$con)
{
    die('Failed to connect to mySQL: ' .mysqli_connect_errno());
}   
}
?>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<body>
<?php
    mb_internal_encoding('UTF-8'); ?>
    <center>
        <div id="fb-root"></div>
        <form method="POST" id="myForm">
            <h1>
                <?php 
                $title = mysqli_query($con, "SELECT `title` FROM titles WHERE c1='a' or c2 ='b'") or die("ERROR: ". mysqli_error($con));
                $title_str = mysqli_fetch_array($title);

                $mystr = mb_convert_encoding($title_str[0], "UTF-8");
                echo "test: ".$mystr;
                        ?>
        </h1><br/>
    </form>
</body>

我已经检查了我的字符编码是否有效,如果我将 $title_str[0] 替换为日文字符串,它是否有效。我在这里错过了什么吗?我不确定为什么编码适用于我手动输入的字符串,而不是我从数据库中获得的字符串。

【问题讨论】:

  • 你确定数据库中字符串的字段可以保存UTF8吗?
  • 是的。我数据库中的所有字符串都是日文字符
  • If from_encoding is not specified, the internal encoding will be used. 来自 PHP.org 的 mb_convert_encoding。我想这可能是您想要的,但请尝试完全按照数据库中的方式指定它(选择其中一个并将其放入 mb_convert_encoding php.net/manual/en/mbstring.supported-encodings.php 的最后一个可选参数中)。我猜 ?s 来自 mb_convert_encoding 无法将输入解密为 UTF-8

标签: php mysql


【解决方案1】:

连接 MySQL 后尝试使用 SET NAMES utf8:

$con=mysqli_connect("host", "user", "pw", "db");   
if (!$con)
{
    die('Failed to connect to mySQL: ' .mysqli_connect_errno());
}

mysqli_query($con, "SET NAMES 'UTF8'") or die("ERROR: ". mysqli_error($con));

正如manual 所说:

SET NAMES 表示客户端将使用什么字符集发送 SQL 对服务器的语句...它还指定服务器应该使用的字符集 用于将结果发送回客户端。

之后就不用mb_convert_encoding了。

【讨论】:

  • 太棒了。这很好用。我确实改变了你的回答。我为 UTF8 添加了单引号并将其大写,因为没有单引号或小写字母就无法工作。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2012-06-11
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
相关资源
最近更新 更多