Php writes mysql Chinese garbled characters. Solution

Source: Internet
Author: User

Php is easy to connect to the database, but if we insert and save data to the mysql database, Chinese garbled characters may occur if the page and database encoding are not unified, next, I will introduce you to the methods for prefixing this problem.

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 mysql_query ("set names 'gb2312'", $ link) to the database connection Statement on the PHP page. 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.