PDO Connection Character Encoding Handling
When establishing a MySQL connection using the PDO (PHP Data Objects) extension, proper character encoding is crucial to ensure data integrity and correct operation. Let's explore how to set the character encoding for a PDO connection.
In traditional mysql_* extension used in your previous code:
mysql_set_charset("utf8",$link); mysql_query("SET NAMES 'UTF8'");
These commands set the character encoding for the connection. However, with PDO, the approach is different.
To set the character encoding for a PDO connection, you can specify it within the connection string itself. For example:
$connect = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
This string appends the charset option to the connection string, specifying the desired encoding, in this case, "utf8mb4". Using this method sets the encoding when the connection is established.
Legacy PHP Versions
However, if you're using PHP version prior to 5.3.6, the charset option in the connection string was ignored. In this case, you must use an alternate method:
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password); $dbh->exec("set names utf8mb4");
Here, the connection is established without specifying the encoding, and the exec() method is used to execute a SQL query to set the character encoding after the connection is established.
The above is the detailed content of How to Properly Set Character Encoding for PDO MySQL Connections?. For more information, please follow other related articles on the PHP Chinese website!