Adopting UTF-8 encoding thoroughly solves the PHP garbled code problem.

by bookmarkscjl on 2008-08-25 15:36:38

It's been a long time since I've written anything. I can't keep posting MVs all the time. By chance, the case at hand involves multi-language requirements, so Freshwater adopted UTF-8 encoding. As a result, I encountered garbled code issues, and thus Freshwater wrote this article.

If you're using MySQL version 4.1 or later, regardless of the character set, always use the default. You don't need to configure MySQL, and it won't produce garbled code examples (Freshwater reminds you again that it should be version 4.1 or higher).

As long as your PHP file containing the INSERT SQL statement is encoded in GB2312, then the data retrieved by the GB2312-encoded PHP file with the SELECT SQL statement will also be GB2312.

Similarly, as long as the PHP file inserting data into the database is UTF-8 encoded, what you input will be UTF-8, and you can retrieve it using a PHP file with UTF-8 encoding.

There's even more interesting stuff. Although everything appears fine on the surface, when you open phpMyAdmin, you'll see garbled characters again because the database character set may not match your program's encoding, which involves MySQL connection collation and other factors. What to do? How will I back up and transfer my data in the future? ... Don't worry; we can fix the garbled code in just two steps.

First, ensure that the PHP files used for inserting data, retrieving data, and template files (if you're using a template engine) are all encoded in UTF-8.

Second, after connecting to the database but before performing CRUD operations, add the following code:

PHP Code:

```php

@mysql_query("SET NAMES 'utf8'");

@mysql_query("SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary");

```

If you're using ADODB, then after instantiating an object, use the following code:

PHP Code:

```php

$db->execute("SET NAMES 'utf8'");

$db->execute("SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary");

```

Everything works perfectly. Not only does the program display without garbled characters, but phpMyAdmin also shows no garbled text.

Freshwater recommends adopting the full UTF-8 encoding approach.