Method One
The problem of using UTF-8 encoding in MySQL database
1. When creating databases and datasheets with phpMyAdmin, set the collation to: "Utf8_general_ci" or execute the statement:
CREATE DATABASE ' dbname ' DEFAULT CHARACTER SET UTF8 COLLATE utf8_general_ci;
When you create a datasheet: If the field is in Chinese, you need to set the collation to: "Utf8_general_ci", if the field is stored in English or numbers, the default is OK.
The corresponding SQL statement, for example:
The code is as follows |
Copy Code |
CREATE TABLE ' Test ' ( ' ID ' INT not NULL, ' Name ' VARCHAR CHARACTER SET UTF8 COLLATE utf8_general_ci not NULL, PRIMARY KEY (' id ') ) ENGINE = MYISAM; |
2. Read and write database in PHP
After connecting to the database:
The code is as follows |
Copy Code |
$connection = mysql_connect ($host _name, $host _user, $host _pass); |
Add two lines:
The code is as follows |
Copy Code |
mysql_query ("Set character set ' UTF8 '");/Read Library mysql_query ("Set names ' UTF8 ')"//write Library |
You can read and write the MySQL database normally.
Another way
Step one command line execution: mysqldump--opt-hlocalhost-uroot-p***--default-character-set=lantin1 dbname >/usr/local/dbname.sql
Step two changes the charset=latin1 of the CREATE TABLE statement in the Dbname.sql file to Charset=utf8
Step three adds a "Set names UTF8" before the INSERT statement in the Dbname.sql file.
Step four dbname.sql transcoding to utf-8 format, we recommend that you use Ultraeditor, you can use the editor's convert->ascii to UTF-8 (Unicode edit) directly, or save the file as a UTF-8 (no BOM) format
Step five command line execution: mysql-hlocalhost-uroot-p***--default-character-set=utf8 new_dbname </usr/local/dbname.sql