(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
注意:
这是改变字符集的首选方法,不推荐使用 mysqli_query() 来设置(如
SET NAMES utf8
)。有关详细信息,请参阅 MySQL 字符集概念部分。