Home > Database > Mysql Tutorial > body text

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

Barbara Streisand
Release: 2024-11-04 13:17:01
Original
1032 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template