
mysqli_set_charset()函数设置默认字符编码
定义和用法
mysqli_set_charset()函数用于指定默认字符集,从mysqli客户端向数据库服务器发送数据的默认字符集。
注意:在 Windows 平台上使用该函数,您需要 MySQL 客户端库 4.1.11 或以上版本(MySQL 5.0 需要 5.0.6 或以上版本)。
语法
mysqli_set_charset($con, charset)
参数
| 序号 | 参数及说明 | 
|---|---|
| 1 | con(必需) 这是一个表示与MySQL Server的连接的对象。 | 
| 2 | charset(必需) 需要设置为默认字符集的名称。 | 
返回值
mysqli_set_charset()函数成功时返回 TRUE, 或者在失败时返回 FALSE。 
PHP版本
此函数最初是在PHP版本5中引入的,并且可以在所有更高版本中使用。
在线示例
以下示例演示了mysqli_set_charset()函数的用法(面向过程风格)-
<?php
   //建立连接
   $con = mysqli_connect("localhost", "root", "password", "mydb");
   //字符集名称
   $res = mysqli_set_charset($con, "utf8");
   print_r($res);
   //关闭连接
   mysqli_close($con);
?>输出结果
1
在线示例
在面向对象风格中,此函数的语法为$con->set_charset();。以下是面向对象风格中此函数的示例;
<?php
   $con = new mysqli("localhost", "root", "password", "test");
   //字符集名称
   $res = $con->set_charset("utf8");
   print($res);
   //关闭连接
   $con -> close();
?>输出结果
1
在线示例
设置默认客户端字符集:
<?php
   $connection_mysql = mysqli_connect("localhost","root","password","mydb");
   
   if (mysqli_connect_errno($connection_mysql)){
      echo "连接MySQL失败: " . mysqli_connect_error();
   }
   
   mysqli_set_charset($connection_mysql,"utf8");
   
   echo mysqli_character_set_name($connection_mysql);
   
   mysqli_close($connection_mysql);  
?>输出结果
utf8
