Overview of the MySQL PHP drivers
2236
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:
Example 20.18. Problems with setting the character set with SQL
<?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
each API.
Example 20.19. 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 20.20. 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 20.21. 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;
Summary of Contents for 5.0
Page 1: ...MySQL 5 0 Reference Manual ...
Page 18: ...xviii ...
Page 60: ...40 ...
Page 396: ...376 ...
Page 578: ...558 ...
Page 636: ...616 ...
Page 844: ...824 ...
Page 1234: ...1214 ...
Page 1427: ...MySQL Proxy Scripting 1407 ...
Page 1734: ...1714 ...
Page 1752: ...1732 ...
Page 1783: ...Configuring Connector ODBC 1763 ...
Page 1793: ...Connector ODBC Examples 1773 ...
Page 1839: ...Connector Net Installation 1819 2 You must choose the type of installation to perform ...
Page 2850: ...2830 ...
Page 2854: ...2834 ...
Page 2928: ...2908 ...
Page 3000: ...2980 ...
Page 3122: ...3102 ...
Page 3126: ...3106 ...
Page 3174: ...3154 ...
Page 3232: ...3212 ...