Home > Database > Mysql Tutorial > How to Fix Broken UTF-8 Encoding with PDO and MySQL?

How to Fix Broken UTF-8 Encoding with PDO and MySQL?

Linda Hamilton
Release: 2024-11-03 19:23:29
Original
586 people have browsed it

How to Fix Broken UTF-8 Encoding with PDO and MySQL?

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

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!

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