文字

mysqli::set_charset

mysqli_set_charset

(PHP 5 >= 5.0.5)

mysqli::set_charset -- mysqli_set_charset设置默认字符编码

说明

面向对象风格

bool mysqli::set_charset ( string $charset )

过程化风格

bool mysqli_set_charset ( mysqli $link , string $charset )

设置在数据库间传输字符时所用的默认字符编码。

参数

link

仅以过程化样式:由 mysqli_connect() mysqli_init() 返回的链接标识。

charset

被设为默认的字符编码名。

返回值

成功时返回 TRUE , 或者在失败时返回 FALSE

注释

Note:

如果在Windows平台上使用该方法,需要4.1.11版或以上的MySQL客户端库,且MySQL版本为5.0.6以上。

Note:

这应该是首选的用于改变字符编码的方法,不建议使用 mysqli_query() 执行SQL请求的SET NAMES ...(如 SET NAMES utf8)。 详见MySQL字符集的概念

范例

Example #1 mysqli::set_charset() example

面向对象风格

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


if ( mysqli_connect_errno ()) {
    
printf ( "Connect failed: %s\n" mysqli_connect_error ());
    exit();
}


if (! $mysqli -> set_charset ( "utf8" )) {
    
printf ( "Error loading character set utf8: %s\n" $mysqli -> error );
} else {
    
printf ( "Current character set: %s\n" $mysqli -> character_set_name ());
}

$mysqli -> close ();
?>

过程化风格

<?php
$link 
mysqli_connect ( 'localhost' 'my_user' 'my_password' 'test' );


if ( mysqli_connect_errno ()) {
    
printf ( "Connect failed: %s\n" mysqli_connect_error ());
    exit();
}


if (! mysqli_set_charset ( $link "utf8" )) {
    
printf ( "Error loading character set utf8: %s\n" mysqli_error ( $link ));
} else {
    
printf ( "Current character set: %s\n" mysqli_character_set_name ( $link ));
}

mysqli_close ( $link );
?>

以上例程会输出:

Current character set: utf8

参见

  • mysqli_character_set_name() - 返回当前数据库连接的默认字符编码
  • mysqli_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • » 关于MySQL支持字符集的列表

用户评论:

[#1] coder at punkass dot com [2006-04-12 11:13:41]

On windows, with "stock" PHP 5.1.2, there is no set_charset function at all. One may have to replace php_mysqli.dll, and libmysql.dll with proper versions, which provided by MySQL at http://dev.mysql.com/downloads/connector/php/

上一篇: 下一篇: