目录

PHP mysqli set_charset() 函数

❮ PHP MySQLi 参考

示例 - 面向对象风格

更改默认客户端字符集:

<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");

if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
}

echo "Initial character set is: " . $mysqli -> character_set_name();

// Change character set to utf8
$mysqli -> set_charset("utf8");

echo "Current character set is: " . $mysqli -> character_set_name();

$mysqli -> close();
?>

查看底部的程序样式示例。


定义和用法

set_charset() / mysqli_set_charset() 函数指定向数据库服务器发送数据或从数据库服务器发送数据时使用的默认字符集。

笔记:要在Windows平台上运行此功能,您需要MySQL客户端库4.1.11或更高版本(对于MySQL 5.0,您需要5.0.6或更高版本)。


语法

面向对象风格:

$mysqli -> set_charset( charset)

程序风格:

mysqli_set_charset( connection, charset)

参数值

Parameter Description
connection Required. Specifies the MySQL connection to use
charset Required. Specifies the default character set

技术细节

返回值: 成功则为真。失败时为 FALSE
PHP 版本: 5.0.5+

示例 - 程序风格

更改默认客户端字符集:

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit;
}

echo "Initial character set is: " . mysqli_character_set_name($con);

// Change character set to utf8
mysqli_set_charset($con,"utf8");

echo "Current character set is: " . mysqli_character_set_name($con);

mysqli_close($con);
?>


❮ PHP MySQLi 参考