Home >Database >Mysql Tutorial >How Do I Set Character Encoding in PHP PDO Connections?
PHP PDO: Character Encoding
Previously, in MySQL_* connections, character encoding was typically set using mysql_set_charset() and mysql_query(). However, these functions are not applicable to PDO connections.
PDO Connection String
For PDO, character encoding can be specified within the connection string itself. Add the charset attribute followed by the desired character set, for example:
"mysql:host=$host;dbname=$db;charset=utf8mb4"
PHP Versions Prior to 5.3.6
In PHP versions prior to 5.3.6, the charset attribute was ignored in the connection string. To set character encoding in these versions, you can use the following approach:
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password); $dbh->exec("set names utf8mb4");
This ensures that the character encoding is set for the PDO connection, allowing for proper handling of character data.
The above is the detailed content of How Do I Set Character Encoding in PHP PDO Connections?. For more information, please follow other related articles on the PHP Chinese website!