UTF-8 Encoding Issues with PDO and MySQL
When using the PHP Data Objects (PDO) library with a MySQL database, you may encounter issues with UTF-8 encoding. Data inserted into the database in UTF-8 may appear as corrupted characters, such as "?????????".
To resolve this, following the guidelines in your framework, execute the queries "SET NAMES utf8" and "SET CHARACTER SET utf8" after establishing the PDO connection. However, if these queries do not rectify the issue, consider the following workaround:
Workaround:
Convert the data into a JSON-encoded string before inserting it into the database using the json_encode function. Retrieve the data using json_decode after fetching it from the database. This approach should resolve the encoding issue.
Optimized Approach:
For PHP versions 5.3.5 and earlier, you can set the UTF-8 character set during connection initialization. This can be achieved with the following code:
$pdo = new PDO( 'mysql:host=hostname;dbname=defaultDbName', 'username', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") );
This ensures that UTF-8 encoding is forced upon the PDO connection, resolving the issue with broken UTF-8 encoding.
The above is the detailed content of How to Solve UTF-8 Encoding Issues with PDO and MySQL?. For more information, please follow other related articles on the PHP Chinese website!