Home > Backend Development > PHP Problem > PHP writes Chinese garbled characters to mysql

PHP writes Chinese garbled characters to mysql

王林
Release: 2023-02-24 09:34:01
Original
4809 people have browsed it

PHP writes Chinese garbled characters to mysql

#The solution to Chinese garbled characters when writing mysql in php is: after establishing a database connection, change the encoding method of the connection to Chinese.

The code is as follows:

$linkID=@mysql_connect("localhost","root","admin");
if(!$linkID)
{
    echo "数据库连接失败!";
}
echo "数据库连接成功!";
mysql_query("SET character_set_connection = GBK",$linkID);//将连接改为中文编码方式。这种方式 
仅能保证插入能正常执行,但是插入之后的数据时???乱码。有待继续解决。
Copy after login

Continuing with the above question, I checked the PHP source file in the Apache directory and found that the encoding method of the page was ANSI, so I changed it to In utf8 format. Then add the following code before executing the SQL statement command:

mysql_query("set names utf8");
Copy after login

This sentence means: Make the encoding of php written to mysql as utf-8
to prevent phpmyadmin Check the Chinese data of mysql and it appears garbled! //Very important! ! Then perform the insert operation again, and the Chinese can be inserted into the database normally, no longer? ? ? The format is garbled.

Summary: If you write Chinese into the Mysql database through PHP, you must ensure that the encoding format of the PHP source file is utf8, the mysql connection must maintain the utf8 format, and the encoding format of the database table is utf8. Ensure these three If the points are consistent, Chinese can be written successfully! !

The above content is for reference only!

Recommended tutorial: PHP video tutorial

The above is the detailed content of PHP writes Chinese garbled characters to mysql. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template