Adopting UTF-8 encoding completely resolves the issue of乱code in PHP. (Note: "乱code" is literally "chaos code" in Chinese, but in this context it refers to "character encoding issues" or "garbled text." A more natural translation might be: "Adopting UTF-8 encoding completely resolves garbled text issues in PHP.")

by bookmarkscjl on 2008-08-26 11:15:11

If you are using MySQL version 4.1 or above, regardless of the character set, always use the default settings. Without configuring MySQL, it will not cause garbled characters (Note again: this applies if you're using version 4.1 or higher).

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

Similarly, if the PHP file used to insert data into the database is encoded in UTF-8, then the data you insert will be in UTF-8, and when retrieving the data, you should use a PHP file encoded in UTF-8 as well.

There's more to consider. Although everything might seem fine so far, when you open phpMyAdmin, you may still see garbled characters because the database character set might not match the encoding of your program. This involves issues such as MySQL connection collation, etc. What can you do? How will you back up and transfer your data in the future?... Don't worry, we can fix the garbled characters in just two steps.

First, make sure that the PHP files for inserting and retrieving data, as well as any template files (if you are 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 will work perfectly. Not only will the program display without garbled characters, but phpMyAdmin will also show no garbled characters.

It is recommended to use UTF-8 encoding throughout.