php连接数据库时候的字符集设置

最好的办法:设置mysql服务器的字符集,当然也可以通过mysql提供的api来设置运行时的字符集

Ideally a proper character set will be set at the server level, and doing this is described within the » Character Set Configuration section of the MySQL Server manual. Alternatively, each MySQL API offers a method to set the character set at runtime.

注意:字符集需要被设置,因为他会影响到每个请求的action,并且会影响到安全(如对mysqli_real_escape_string()mysql_real_escape_string()PDO::quote())对这些函数产生影响。(用query设置的字符集,这些函数不会用到)

The character set and character escaping

The character set should be understood and defined, as it has an affect on every action, and includes security implications.

For example, the escaping mechanism (e.g., mysqli_real_escape_string() for mysqli, mysql_real_escape_string() for mysql, and PDO::quote() for PDO_MySQL) will adhere(坚持; 追随; ) to this setting. It is important to realize that these functions will not use the character set that is defined with a query, so for example the following will not have an effect on them:

<?php

$mysqli = new mysqli("localhost""my_user""my_password""world");

// Will not affect $mysqli->real_escape_string();
$mysqli->query("SET NAMES utf8");

// Will not affect $mysqli->real_escape_string();
$mysqli->query("SET CHARACTER SET utf8");

// But, this will affect $mysqli->real_escape_string();
$mysqli->set_charset('utf8');

?>
 

Below are examples that demonstrate how to properly alter the character set at runtime using each API.

Example #2 Setting the character set example: mysqli

<?php

$mysqli = new mysqli("localhost""my_user""my_password""world");

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());
}

print_r$mysqli->get_charset() );

?>

Example #3 Setting the character set example: pdo_mysql

Note: This only works as of PHP 5.3.6.

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world;charset=utf8"'my_user''my_pass');
?>

Example #4 Setting the character set example: mysql

<?php

$conn mysql_connect("localhost""my_user""my_pass");
$db   mysql_select_db("world");

if (!mysql_set_charset('utf8'$conn)) {
    echo "Error: Unable to set the character set.\n";
    exit;
}

echo 'Your current character set is: ' .  mysql_client_encoding($conn);

?>
 
参考:http://php.net/manual/en/mysqlinfo.concepts.charset.php#mysqlinfo.concepts.charset
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值