Home > Backend Development > PHP Problem > What to do if php saves garbled characters to mysql

What to do if php saves garbled characters to mysql

藏色散人
Release: 2023-03-10 22:36:02
Original
1791 people have browsed it

Solutions to garbled characters stored in MySQL in php: 1. Change the encoding format of the PHP source file to utf8; 2. The mysql connection must maintain the utf8 format; 3. Change the encoding format of the database table to utf8.

What to do if php saves garbled characters to mysql

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

What should I do if php is stored in mysql with garbled characters?

An example solution to the Chinese garbled code when php writes to mysql

The solution to the Chinese garbled code when php writes to mysql is: after establishing the database connection, change the encoding method of the connection for 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

Only ensures that the insertion can be executed normally, but when inserting the subsequent data? ? ? Garbled characters. To be further resolved.

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 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

This can prevent mysql from being viewed in phpmyadmin Chinese data is 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! !

Recommended learning: "PHP Video Tutorial"

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

Related labels:
php
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