PHP-MYSQL Chinese garbled problem.
Jul 09, 2016 am 09:09 AMMulti-language support has been introduced since MySQL 4.1, but Chinese characters inserted using PHP will appear garbled. No matter what encoding is used, it will not work.
Solving this problem is actually very simple.
1. When creating the table, set the encoding type to gb2312_chinese_ci.
2. Add a line mysql_query("SET NAMES 'gb2312'",$link); to the database connection statement on the PHP page; for example
$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);
Add this line to both the writing page and the reading page. In this way, the Chinese in MYSQL can be displayed normally.
Related information:
Multi-language support has been introduced since MySQL 4.1, and some features have surpassed other database systems.MySQL 4.1's character set support (Character Set Support) has two aspects: character set (Character Set Support) set) and sorting method (Collation). Support for character sets is refined to four levels: Server, database, table and connection.
To view the system's character set and sorting settings, you can use the following two commands:!
mysql> show variables like 'character_set_%';
----------- --------------- -------------------------------
| Variable_name | Value |
-------------------------- -------------------- --------
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
-------------------------- - ----------------------------
7 rows in set (0.00 sec)
mysql> show variables like 'collation_ %';
--------------------------- ------------------
| Variable_name | Value |
----------------------- -------------------
| collation_connection | latin1_swedish_ci |
| collation_database | latin1_swedish_ci |
| collation_server | latin1_swedish_ci |
----------------------- -- ------------------
3 rows in set (0.00 sec)
The values ??listed above are the system default values. (It’s strange how the system defaults to the Swedish sorting method of latin1)...
When we access the MySQL database through PHP in the original way, even if the default character set of the table is set to utf8 and encoded through UTF-8 Send a query and you will find that the data stored in the database is still garbled. The problem lies in this connection layer. The solution is to execute the following sentence before sending the query:
set names 'utf8';
It is equivalent to the following four instructions:
set character_set_client = utf8;
set character_set_results = utf8;
set character_set_connection = utf8;
set collation_connection = utf8_general_ci
by The query submitted on the default web page is gb2312 (can be seen in the form page meta), and mysql treats it as utf8 by default (you can check the character_set_client=utf8), so it must be garbled. In the same way, the result returned by mysql has been converted into Character_set_results is encoded (regardless of the encoding of the table). It also defaults to utf8, and the web page treats it as gb2312, so there must be titles and other data generated by the data. The field read by the library is garbled, but other PHP text is not garbled.
Solution (by Yi Jian Piaoxue):
When installing mysql5.0, you need to select the utf8 character set (you don’t need to select the utf8 character set when creating databases and fields with phpmyadmin), and After php establishes the connection, send
$link = mysql_connect('localhost', 'root', 'root');
mysql_query("SET NAMES 'utf8'",$link);
At this time we What I see on the web page is still garbled, but it is no longer ????. When I check the source file of the web page, it is completely normal. Open the php source file with notepad, don't save it as utf8 encoding, refresh the web page, and everything is done.
Or, of course, you still need to install utf8 when installing. Send set names 'gb2312' in php, and save the php file as Notepad's default ansi, which can also display Chinese correctly.
But always You can't send SET NAMES 'utf8' every time you connect. I haven't found a way to completely solve it.
When installing mysql in this way, the default character set is selected as utf8, which brings another problem. After we enter the mysql console in command.exe, the query results become garbled again. We can enter mysql>set names 'gbk';
or
mysql>set names 'gb2312';
is equivalent to telling the mysql client to use the gb2312 character set, and the result is correct. gb2312 is a sub-child of GBK Set.

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

Execution of SELECT queries using PHP's preprocessing statements can effectively prevent SQL injection and improve security. 1. Preprocessing statements separate SQL structure from data, send templates first and then pass parameters to avoid malicious input tampering with SQL logic; 2. PDO and MySQLi extensions commonly used in PHP realize preprocessing, among which PDO supports multiple databases and unified syntax, suitable for newbies or projects that require portability; 3. MySQLi is specially designed for MySQL, with better performance but less flexibility; 4. When using it, you should select appropriate placeholders (such as? or named placeholders) and bind parameters through execute() to avoid manually splicing SQL; 5. Pay attention to processing errors and empty results to ensure the robustness of the code; 6. Close it in time after the query is completed.

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

To securely connect to a database in PHP, several critical steps are required. First, use PDO to prevent SQL injection with preprocessing statements to ensure that SQL logic is separated from data; second, store database credentials in non-Web root directory or use environment variable management through .env files, and avoid submission to version control; third, enable SSL encrypted database connections to ensure that the latest certificate is held; finally, properly handle error information, record errors internally instead of showing detailed content to users, thereby avoiding the leakage of sensitive information. The above measures jointly ensure the security of database connections.
