utf 8 - PHP and MySQLi UTF8


utf 8 - PHP and MySQLi UTF8

我的表字符集是 utf8,它的排序规则是 utf8.现在我有这段代码:

   $mysqli = new mysqli("localhost", "root", "", "Amoozeshgah");
            if (mysqli_connect_errno()) {
                  printf("Connect failed: %s'n", mysqli_connect_error());
            }
          if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s'n", $mysqli->error);
} else {
    printf("Current character set: %s'n", $mysqli->character_set_name());
}
        mysql_set_charset('utf8');
            if ($stmt = $mysqli->prepare("SELECT About_Title FROM Tbl_About WHERE About_Id=?")) {
                $city = 8;
               /* bind parameters for markers */
                $stmt->bind_param("s", $city);
              /* execute query */
                $stmt->execute();
               /* bind result variables */
                  $result = $stmt->get_result();
             /* fetch value */
            while ($myrow = $result->fetch_assoc()) {
        // use your $myrow array as you would with any other fetch
        printf("%s is in district %s'n", $city, $myrow['About_Title']);
        print("shod");
    }

但输出是:

Current character set: utf8 8 is in district نتمنتشس shod

我能做什么?编辑:我替换了:

if (!$mysqli->set_charset("utf8")) {
        printf("Error loading character set utf8: %s'n", $mysqli->error);
    } else {
        printf("Current character set: %s'n", $mysqli->character_set_name());
    }
            mysql_set_charset('utf8');

$mysqli->set_charset("utf8")

但没有区别。

请将mysql_set_charset('utf8');替换为$mysqli->set_charset("utf8") :-)

or mysqli_set_charset($this->mysqli,"utf8");
mysqli_set_charset($conn,"utf8");
以防

万一您在代码中使用"json_encode",例如:

json_encode($rows);

只需将其更改为:

json_encode($rows,JSON_UNESCAPED_UNICODE);

有趣的场景,可能会帮助其他人。没有技术细节/解释,而只是正确方向的推动/线索。

场景:基于成功/已验证的 IPN PayPal事务远程自动创建用户帐户。Mysqli 查询创建用户和用户元数据,但该数据的值包含隐藏的格式字符,并使表单处理中调用的数据的使用无效。非常简单的解决方案,无需更改/更改任何现有的数据库表。基本上,这可以确保您的数据只是ASCII可打印字符,甚至使用$mysqli->set_charset("utf8");并不是那么重要,因为您正在准备要处理和输入"ASCII clean"的数据。

    $create_ipn = $mysqli->prepare("INSERT INTO xxx_somewhere (some_ipn_parameter , email, domain, item) VALUES (?, ?, ?, ?)");
    $create_ipn->bind_param("ssss", $some_ipn_parameter, $email, $domain, $item);
    $some_ipn_parameter = preg_replace( '/[^'x01-'x7F]/', "", 'the_actual_ipn_data' );
    $email = 'edward@ait-pro.com';
    $domain = '';
    $item = 'Test';
    $create_ipn->execute();         

从数据库获取数据时,您不仅要正确获取数据,还需要在页面上正确显示数据,因此请尝试在页面标题中使用 UTF-8 编码:

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

<meta charset="utf-8">

这是我的问题和解决方案,感谢Rohit Kumar Choudhary。

在 php 文件中添加以下内容 在代码顶部添加以下内容

header('Content-Type: text/plain; charset=utf-8');