对于我的 mysql 数据库。
mysql> show variables like 'character%';
+--------------------------+-------------------------------+
| Variable_name | Value |
+--------------------------+-------------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | gb2312 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | F:wampmysqlsharecharsets |
+--------------------------+-------------------------------+
mysql> show variables like "collation%";
+----------------------+-------------------+
| Variable_name | Value |
+----------------------+-------------------+
| collation_connection | utf8_general_ci |
| collation_database | gb2312_chinese_ci |
| collation_server | utf8_general_ci |
+----------------------+-------------------+
我想在 php7 中使用 mysqli 选择一些信息。 名为getdata1.php
的文件以utf-8
编码。
My getdata1.php file.
<?php
header("Content-type: text/html; charset=utf-8");
$mysqli = new mysqli("localhost", "root", "xxxxxx", "student");
$sql = "SELECT * FROM student";
$result = $mysqli->query($sql);
$row = $result->fetch_assoc();
print_r($row);
$result->close();
$mysqli->close();
?>
我得到了以下输出。
Array ( [ID] => 1 [学号] => 11410104 [姓名] => 陈XX)
据我所知,中文字符既可以在 php 的关联数组的关联键中使用,也可以用于值。
现在我想用$row["姓名"]
获取数据。
使用以下文件也getdata2.php
utf-8
编码,我一无所获。
My getdata2.php file.
<?php
header("Content-type: text/html; charset=utf-8");
$mysqli = new mysqli("localhost", "root", "xxxxxx", "student");
$sql = "SELECT * FROM student";
$result = $mysqli->query($sql);
while ($row = $result->fetch_row()) {
printf ("%s n", $row["姓名"]);
}
$result->close();
$mysqli->close();
?>
检查 apache 中的日志文件。
Notice: Undefined index: xe5xa7x93xe5x90x8d in F:\wamp\apache2\htdocs\getdata2.php on line 7
[Sun Aug 12 20:25:23.217182 2018] [:error] [pid 12204:tid 1264] [client 127.0.0.1:54023]
xe5xa7x93xe5x90x8d
字符串是姓名
的utf-8编码。
python3
>>> b"xe5xa7x93xe5x90x8d".decode("utf-8")
'姓名'
如何在 php7 的 mysqli 查询中使用汉字作为关联键?
fetch_row()
生成一个索引数组。
您在需要数字时提供中文字符,请将函数更改为fetch_assoc()
。
为了使您能够在将来实现这一点,您应该在卡住时编写var_export($result->fetch_row());
,以便您可以看到 1-dim 数组中的实际内容,并确定元素访问尝试失败的原因。
作为良好的常规做法,您应该将查询中的*
替换为您打算使用的单独列 - 这样结果集就不会包含任何不必要的膨胀。