最好的办法:设置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 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);
?>