1. Reasons for garbled characters
When using PHP to connect to MySQL, if the character set of MySQL is inconsistent with the character set of PHP, garbled characters will appear. The specific reasons are as follows:
MySQL’s character set is inconsistent with PHP’s character set
MySQL’s default character set is UTF-8, while PHP’s default character set is ISO-8859- 1. If you do not specify a character set in your PHP code, PHP will use the ISO-8859-1 character set. At this time, if the data queried from MySQL contains UTF-8 characters, garbled characters will appear.
The character set of the MySQL data table is inconsistent with the character set of the MySQL server
In MySQL, each data table has a default character set. If the character set of the data table is inconsistent with the character set of the MySQL server, garbled characters may appear.
The way PHP connects to MySQL is incorrect
When connecting to MySQL, PHP has a variety of connection methods, such as mysql_connect, mysqli_connect, PDO, etc. Different connection methods will use different encoding methods. If selected improperly, it will lead to garbled code problems.
2. Solve the garbled code problem
In response to the above reasons, the following measures can be taken to solve the garbled code problem.
Specify character set for PHP
In PHP code, solve the problem of garbled characters by specifying the character set. You can use the following code:
header('Content-Type:text/html;charset=utf-8');
Modify the MySQL default character set
You can modify the MySQL default character set in the MySQL configuration file my.cnf. Open the file, find the [mysqld] section, and add the following code:
character-set-server=utf8
Modify the character set of the MySQL data table
You can modify the data table through the following statement Character set:
ALTER TABLE {table_name} CONVERT TO CHARACTER SET utf8;
Modify the way PHP connects to MySQL
You can use PDO to connect to MySQL and specify the character set when connecting, as follows:
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', 'password');
If you use mysqli to connect to MySQL, you can specify the character set through the following code:
$mysqli = mysqli_connect('localhost', 'root', 'password', 'test'); mysqli_set_charset($mysqli, 'utf8');
Save the PHP file in UTF-8 encoding format
If your PHP file contains Chinese characters, you must save the file in UTF-8 encoding format when saving the file, otherwise garbled characters will appear.
The above is the detailed content of How to solve the garbled problem of php connection to mysql. For more information, please follow other related articles on the PHP Chinese website!