(PHP 5 >= 5.0.5, PHP 7, PHP 8)
mysqli::set_charset -- mysqli_set_charset — 设置客户端字符集
面向对象风格
过程化风格
设置客户端与数据库间传输数据时所用的字符集。
If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR
) and the requested operation fails,
a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT
,
a mysqli_sql_exception is thrown instead.
示例 #1 mysqli::set_charset() 示例
面向对象风格
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
printf("Initial character set: %s\n", $mysqli->character_set_name());
/* change character set to utf8mb4 */
$mysqli->set_charset("utf8mb4");
printf("Current character set: %s\n", $mysqli->character_set_name());
过程化风格
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');
printf("Initial character set: %s\n", mysqli_character_set_name($link));
/* change character set to utf8mb4 */
mysqli_set_charset($link, "utf8mb4");
printf("Current character set: %s\n", mysqli_character_set_name($link));
以上示例的输出类似于:
Initial character set: latin1 Current character set: utf8mb4
注意:
如果在 Windows 平台上使用该方法,需要 MySQL 客户端库版本 4.1.11 或以上(且 MySQL 5.0 版本需要 5.0.6 及以上)。
注意:
这是改变字符集的首选方法,不推荐使用 mysqli_query() 来设置(如
SET NAMES utf8
)。有关详细信息,请参阅 MySQL 字符集概念部分。