How to solve the Chinese garbled code in php mysql?
php Mysql Chinese garbled solution: first use the meta tag to set the "page declaration encoding" to GB2312 and UTF-8; then use mysql_query() to set the "database connection encoding" and ensure the "page declaration encoding" It can be consistent with the "database connection encoding".
Recommended tutorials: mysql video tutorial, PHP video tutorial
Generally speaking, there are two reasons for the appearance of garbled characters. First, it is due to an error in the encoding (charset) setting, which causes the browser to parse with the wrong encoding, resulting in a screen full of messy "heavenly books". Second, the file is Open and then save in the wrong encoding. For example, a text file was originally encoded in GB2312, but it was opened in UTF-8 encoding and then saved. To solve the above garbled code problem, you first need to know which aspects of development involve encoding:
1. File encoding: refers to the encoding in which the page file (.html, .php, etc.) itself is saved. . Notepad and Dreamweaver will automatically recognize the file encoding when opening the page, so there will be less problems. However, ZendStudio does not automatically recognize the encoding. It will only open the file in a certain encoding according to the configuration of the preferences. If you accidentally open the file with the wrong encoding while working, garbled characters will appear as soon as you save it after making the modification.
2. Page declaration encoding: In the HTML code HEAD, you can use (this sentence It must be written in front of
3. Database connection encoding: refers to which encoding is used to transmit data to the database when performing database operations. It should be noted here that it should not be confused with the encoding of the database itself, such as MySQL internal The default is latin1 encoding, which means that Mysql stores data in latin1 encoding, and data transmitted to Mysql in other encodings will be converted into latin1 encoding.
I know where encoding is involved in WEB development, and You will know the reason for the garbled characters: the above three encoding settings are inconsistent. Since most of the various encodings are compatible with ASCII, English symbols will not appear, and Chinese characters will be unlucky. Here are some common error situations and solutions:
1. The database uses UTF8 encoding, and the page declaration encoding is GB2312. This is the most common cause of garbled characters. At this time, the direct SELECT data in the PHP script will be garbled. You need to use it before querying:
mysql_query("SET NAMES GBK"); //或 mysql_query("SET NAMES GB2312");
To set the MYSQL connection encoding, ensure that the page declaration encoding is consistent with the connection encoding set here (GBK is an extension of GB2312). If the page is UTF-8 encoded, you can use:
mysql_query("SET NAMES UTF8");
Note that it is UTF8 instead of the commonly used UTF-8. If the encoding declared on the page is consistent with the internal encoding of the database, you do not need to set the connection encoding.
Note: In fact, the data input and output of MYSQL is faster than the above. It is more complicated. Two default encodings are defined in the MYSQL configuration file my.ini, which are default-character-set in [client] and default-character-set in [mysqld] to set the default client respectively. The encoding used within the connection and database. The encoding we specified above is actually the command line parameter character_set_client when the MYSQL client connects to the server, which tells the MYSQL server what encoding the client data received is, instead of using the default encoding.
2. The page declaration encoding is inconsistent with the encoding of the file itself. This rarely happens, because if the encoding is inconsistent, what the artist sees in the browser when making the page is garbled code. More often, some small modifications are made after publishing. BUG, caused by opening the page with the wrong encoding and then saving it. Or you use some FTP software to directly modify files online, such as CuteFTP. Due to incorrect software encoding configuration, the wrong encoding is converted.
3. Some friends who rent virtual hosts still have garbled codes even though the above three encodings are set correctly. For example, if the web page is encoded in GB2312, it is always recognized as UTF-8 when opened by browsers such as IE. The HEAD of the web page has already stated that it is GB2312. After manually changing the browser encoding to GB2312, the page displays normally. The reason is that the server Apache sets the global default encoding of the server and adds AddDefaultCharset UTF-8 in httpd.conf. At this time, the server will first send the HTTP header to the browser, and its priority is higher than the encoding declared in the page. Naturally, the browser will recognize it incorrectly. There are two solutions. Administrators should add AddDefaultCharset GB2312 to the configuration file of their own virtual machine to override the global configuration, or configure it in .htaccess in their own directory.
Solution to garbled codes
To solve the garbled code problem, you must first figure out what encoding your database uses. If not specified, the default is latin1.
The three character sets we use most should be gb2312, gbk, and utf8.
那么我们如何去指定数据库的字符集呢?下面也gbk为例
【在MySQL Command Line Client创建数据库】
mysql> CREATE TABLE `mysqlcode` ( -> `id` TINYINT( 255 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY , -> `content` VARCHAR( 255 ) NOT NULL -> ) TYPE = MYISAM CHARACTER SET gbk COLLATE gbk_chinese_ci; Query OK, 0 rows affected, 1 warning (0.03 sec) mysql> desc mysqlcode; +---------+-----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+-----------------------+------+-----+---------+----------------+ | id | tinyint(255) unsigned | NO | PRI | | auto_increment | | content | varchar(255) | NO | | | | +---------+-----------------------+------+-----+---------+----------------+ 2 rows in set (0.02 sec)
其中后面的TYPE = MYISAM CHARACTER SET gbk COLLATE gbk_chinese_ci;
就是指定数据库的字符集,COLLATE (校勘),让mysql同时支持多种编码的数据库。
当然我们也可以通过如下指令修改数据库的字符集
alter database da_name default character set 'charset'.
客户端以 gbk格式发送 ,可以采用下述配置:
SET character_set_client='gbk' SET character_set_connection='gbk' SET character_set_results='gbk'
这个配置就等价于 SET NAMES 'gbk'。
现在对刚才创建的数据库操作
mysql> use test; Database changed mysql> insert into mysqlcode values(null,'php爱好者'); ERROR 1406 (22001): Data too long for column 'content' at row 1
没有指定字符集为gbk,插入时出错
mysql> set names 'gbk'; Query OK, 0 rows affected (0.02 sec)
指定字符集为 gbk
mysql> insert into mysqlcode values(null,'php爱好者'); Query OK, 1 row affected (0.00 sec)
插入成功
mysql> select * from mysqlcode; +----+-----------+ | id | content | +----+-----------+ | 1 | php爱好着 | +----+-----------+ 1 row in set (0.00 sec)
在没有指定字符集gbk时读取也会出现乱码,如下
mysql> select * from mysqlcode; +----+---------+ | id | content | +----+---------+ | 1 | php??? | +----+---------+ 1 row in set (0.00 sec)
【在phpmyadmin创建数据库,并指定字符集】
表类型根据自己需要选,这里选MyISAM(支持全文检索);
整理选择 gbk_chinese_ci 也就是gbk字符集
gbk_bin 简体中文, 二进制。gbk_chinese_ci 简体中文, 不区分大小写。
在刚才创建的数据库插入数据库
再浏览时发现是乱码
为什么呢?是因为数据库为gbk字符集,而我们操作时没有指定为gbk
回到数据库首页
可以看到 mysql 连接校对默认的latin1_bin。我们将其改为gbk_chinese_ci
再插入一条数据。看,这条已经正常了
【解决php读取数据库乱码】
仍以数据库mysqlcode为例
<?php $conn = mysql_connect("localhost","root","89973645"); mysql_query("set names 'gbk'");//这就是指定数据库字符集,一般放在连接数据库后面就系了 mysql_select_db("test"); $sql = "select * from mysqlcode"; $result = mysql_query($sql,$conn); ?> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>mysql 字符编码</title> </head> <body> <table width="300" height="32" border="1" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="71" align="center">id</td> <td width="229" align="center">内容</td> </tr> <?php while($row = mysql_fetch_assoc($result)){ echo " <tr> <td align=/"center/">".$row['id']."</td> <td>".$row['content']."</td> </tr>"; }?> </table> </body> </html> <?php mysql_free_result($result);?>
如果我们将mysql_query("set names 'gbk'");
注释掉,肯定时乱码
加上那句又正常了
一句
你数据库用什么编码,在对数据库操作之前就set names '你的编码';
更多编程相关知识,请访问:编程学习网站!!
The above is the detailed content of How to solve the Chinese garbled code in php mysql?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.
