PHP PDO: Character Set and Collation
In the legacy mysql_* API, you used mysql_set_charset() and mysql_query("SET NAMES 'UTF8'") to set the character set and collation. With PDO, these functions are no longer necessary. Instead, you specify the character set and collation in the connection string.
Connection String with Character Set and Collation
The following code shows how to specify the character set and collation in the connection string:
$connect = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
This will connect to the database and set the character set to UTF-8.
Prior to PHP 5.3.6
Prior to PHP 5.3.6, the charset option in the connection string was ignored. If you are using an older version of PHP, you must set the character set using the exec() method:
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password); $dbh->exec("set names utf8mb4");
The above is the detailed content of How Do I Set Character Set and Collation in PHP PDO?. For more information, please follow other related articles on the PHP Chinese website!