PDO Character Encoding
In previous database connections using MySQL, it was common to set the character set manually using mysql_set_charset() and mysql_query("SET NAMES 'UTF8'"). However, when using PDO (PHP Data Objects), the charset can be specified in the connection string.
PDO Connection String with Character Set
To set the character set in the connection string, add the charset option to the PDO constructor. For example:
$connect = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
PHP Versions Prior to 5.3.6
If you are using PHP versions prior to 5.3.6, the charset option in the connection string was ignored. In this case, you can use the following code to set the character set after connecting:
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password); $dbh->exec("set names utf8mb4");
By using these methods, you can ensure that your PDO connections have the correct character encoding for your application.
The above is the detailed content of How to Set Character Encoding in PDO Database Connections?. For more information, please follow other related articles on the PHP Chinese website!