Fixing Broken UTF-8 Encoding with PDO and MySQL
When using PDO with a MySQL database in PHP, inserting UTF-8 encoded data often results in garbled characters or question marks in the database. This can be a frustrating issue, especially when dealing with languages like Arabic.
To resolve this issue, simply set the MySQL connection to use UTF-8 encoding from the start. Here's how you can do it:
PHP Code:
<code class="php">$pdo = new PDO( 'mysql:host=hostname;dbname=defaultDbName', 'username', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") );</code>
Warning: This solution is only applicable to PHP versions 5.3.5 and below. For PHP versions 5.3.6 and later, refer to alternative answers provided on the original thread.
By setting the initial command to "SET NAMES utf8", PDO automatically sends this query to the server after establishing the connection, ensuring that all subsequent queries use UTF-8 encoding. This eliminates the need for additional SET NAMES or SET CHARACTER SET queries after establishing the connection.
The above is the detailed content of How to Fix Broken UTF-8 Encoding with PDO and MySQL?. For more information, please follow other related articles on the PHP Chinese website!