Home  >  Article  >  Database  >  Why does my UTF-8 encoded data appear as gibberish when using PDO with MySQL?

Why does my UTF-8 encoded data appear as gibberish when using PDO with MySQL?

Barbara Streisand
Barbara StreisandOriginal
2024-11-04 13:17:011034browse

Why does my UTF-8 encoded data appear as gibberish when using PDO with MySQL?

PDO MySQL UTF-8 Encoding Issues

Problem: When utilizing PDO with a MySQL database in PHP, UTF-8 encoded data inserted into the database appears as gibberish.

Possible Cause:

  • Incorrect handling of character set and encoding settings during database connection establishment.

Solution:

  • Ensure proper character set and encoding configuration upon database connection initialization. Use the following syntax:
<code class="php">$pdo = new PDO( 
    'mysql:host=hostname;dbname=defaultDbName', 
    'username', 
    'password', 
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") 
); </code>

This line forces UTF-8 encoding on the PDO connection and resolves the encoding issues.

Warning: This solution is intended for PHP versions 5.3.5 and earlier. For PHP versions 5.3.6 and up, refer to alternative solutions provided elsewhere.

The above is the detailed content of Why does my UTF-8 encoded data appear as gibberish when using PDO with MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn