php连接数据库并锁定字符集,php连接数据库时候的字符集设置

本文介绍了如何在MySQL服务器级别设置字符集,以及如何使用不同的MySQL API在运行时更改字符集。强调了字符集设置的重要性,因为它影响每个数据库操作并涉及安全性。示例展示了mysqli、PDO_MySQL和mysql API的用法来设置字符集。
摘要由CSDN通过智能技术生成

最好的办法:设置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,并且会影响到安全(如对

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:

$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

$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.

$pdo = new PDO("mysql:host=localhost;dbname=world;charset=utf8", ‘my_user‘, ‘my_pass‘);

?>

Example #4 Setting the character set example: mysql

$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

原文:http://www.cnblogs.com/Alight/p/4078918.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值