The mysql operation in php is very simple. However, when I was working on a small tool recently, I found that Chinese characters are garbled in the database written to mysql by php. This garbled problem has plagued me for a long time, clearly English characters are written normally, but Chinese characters are garbled!
At first I felt like I didn't set up the UTF-8 character set when I set up the mysql database, but then I found that even if I set this character set, it still couldn't solve the problem, the strings written to mysql still garbled.
Solving this problem is actually very simple.
1. Set the encoding type to gb2312_chinese_ci when creating the table.
2. Add a row to the database connection statement on the PHP pageMysql_query ("set names 'gb2312 '", $ link );For example
The code is as follows: |
Copy code |
$ Db_host = "localhost "; $ Db_user = "root "; $ Db_password = "password "; $ Db_name = "test "; $ Link = mysql_connect ($ db_host, $ db_user, $ db_password ); Mysql_query ("set names 'gb2312 '", $ link ); $ Db = mysql_select_db ($ db_name, $ link ); $ Query = "select * from user "; $ Result = mysql_query ($ query ); |
This line is added to both the write and read pages, so that Chinese characters in MYSQL can be displayed normally.
Another method is to modify the configuration file my. cnf.
The code is as follows: |
Copy code |
[Mysqld] Default-character-set = utf8 |
Restart MYSQL. If this is changed, set character_set_server to utf8.
Now we can solve the problem of php writing mysql Chinese garbled characters. Of course, we mainly pay attention to the encoding between the page and the database and then use mysql_query () for setting.