The best way: Set the character set of the MySQL server, and of course you can set the runtime by using the API provided by MySQL.
Ideally a proper character set would be set at the server level, and doing this is described within The»character set Con figuration section of the MySQL Server manual. Alternatively, each of the MySQL API offers a method to set the character set at runtime.
Note: The character set needs to be set because he affects each requested action, and it affects security (such as mysqli_real_escape_string (),mysql_real_escape_string (), pdo::quote ()) has an effect on these functions. (the character set used by query, these functions are not used)
The character set and character escaping
The character set should is understood and defined, as it has a affect on every action, and includes security implication S.
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) would adhere (insisted; Followers ) to this setting. It's important to realize that these functions won't use the character set that's defined with a query, so for Exampl E The following would not have a effect on them:
<?php
$mysqli= newMysqli("LocalHost","My_user","My_password","World");
Would not affect $mysqli->real_escape_string ();
$mysqli-Query("SET NAMES UTF8");
Would not affect $mysqli->real_escape_string ();
$mysqli, query("set CHARACTER set UTF8");
But, this would affect $mysqli->real_escape_string ();
$mysqli-set_charset(' UTF8 ');
?>
Below is 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= newMysqli("LocalHost","My_user","My_password","World");
if (!$mysqli-Set_charset(' UTF8 ')) {
Printf("Error loading Character Set UTF8:%s\n", $mysqli ->< Span style= "color: #0000bb;" >error);
} else {
printf (, $mysqli -> ());
}
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();
if (! Mysql_set_charset UTF8 ' , $conn ) {
echo "Error: unable to set the character set.\n " exit;
}
Echo "your current character set is: ' Reference: Http://php.net/manual/en/mysqlinfo.concepts.charset.php#mysqlinfo.concepts.charset
Character Set settings when PHP connects to a database