繁体   English   中英

编码地狱。 MySQL,PHP和UTF-8

[英]Encoding hell. Mysql, php and utf-8

执行比较短语的查询是一件麻烦事。 查看以下配置以了解我的问题。


sql.sql

create user "myStore"@"localhost" identified by "1234"; grant all privileges on myStore.* TO "myStore"@"localhost";

create database myStore character set utf8 collate utf8_general_ci;

use myStore;

create table item (
    item_id integer not null,
    name varchar(60) not null,

    primary key (item_id)
);

alter table item engine=innodb default charset=utf8 collate=utf8_bin;

insert into item (item_id, name) values (0, "apple"), (1, "maça");

my.cnf

[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8

mysql>显示变量,例如'collat​​ion%';

+----------------------+-----------------+
| Variable_name        | Value           |
+----------------------+-----------------+
| collation_connection | utf8_general_ci |
| collation_database   | utf8_unicode_ci |
| collation_server     | utf8_unicode_ci |
+----------------------+-----------------+

mysql>显示变量,例如'character_set%';

+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | utf8                       |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | utf8                       |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+

index.php

<?php
    try {
        header ('Content-Type: text/html; charset=utf-8'); 

        $mysqli = new mysqli ("localhost", "myStore", "1234", "myStore");

        if ($mysqli->connect_error) throw new exception ("Error (" . $mysqli->connect_errno . "). " . $mysqli->connect_error);

        $sql = $mysqli->prepare ("select item_id, name from item where name = '" . utf8_decode ("maça") ."'");

        if (! $sql) throw new exception ($mysqli->error);

        $sql->execute ();

        $sql->bind_result ($item_id, $name); 

        while ($sql->fetch ()) echo $item_id . " - " . utf8_encode ($name);

        $sql->close ();
    }
    catch (exception $e) {
        echo $e;
    }
?>

如您所见,在将字符串发送给MySQL之前,我必须对其进行解码,然后再次对其进行编码。

我真的不知道这是怎么回事,有没有办法避免这些编码和解码功能? 谢谢。

mysql>显示变量,例如'character_set%';

 +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 | 

这些变量是特定于会话的。 请确保他们在适当的会议通过调用设置为您的客户SET NAMES ' charset_name '的互动过程中mysql会话,或mysqli::set_charset ( string $charset )从PHP。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM