执行比较短语的查询是一件很痛苦的事情。请查看以下配置以了解我的问题。
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> 显示像“collation%”这样的变量;
+----------------------+-----------------+
| 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> SHOW VARIABLES LIKE 'character_set%';
+--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8 | | character_set_connection | utf8 |
这些变量是特定于 session 的。请调用 SET NAMES '<em>charset_name</em>'
确保在您的 session 期间为您的客户进行适当的设置。在交互式 mysql
期间 session ,或 <strong>mysqli::set_charset</strong> ( string <em>$charset</em> )
来自 PHP。
关于php - 编码 hell 。 MySQL、PHP 和 utf-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12327325/