In the PHP development process, saving data to the database is often involved. However, sometimes there will be garbled characters when saving data to the database. This article will focus on the problem of garbled characters when saving PHP data to the database, and how to solve it.
1. Cause of the problem
When PHP updates the MySQL database, if the character sets of PHP and MySQL are inconsistent, garbled characters may occur. To address this issue, the correct character set needs to be specified in the code.
2. Solution
You can modify the character set in the MySQL database through the following command
SET NAMES 'utf8mb4';
This command is only valid for the current connection. If permanent modification is required, it needs to be modified in the MySQL configuration file. The modification method is as follows:
[mysqld] character-set-server = utf8mb4 collation-server = utf8mb4_unicode_ci
Just add a code when connecting to the database:
mysqli_set_charset($mysqli, "utf8mb4");
Use the function header()
in PHP to set the http header, as follows:
header("Content-type:text/html;charset=utf-8");
Set it like this All character sets output to the browser are UTF-8.
In PHP, you can also specify the encoding method for saving data to the database:
mysqli_query($link, "SET NAMES 'utf8mb4'");
Among them, $link
is the object connecting to the MySQL database.
When creating the data table, you need to specify the character set:
CREATE TABLE `mytable`(`id` INT, `name` VARCHAR(50)) DEFAULT CHARSET=utf8mb4;
Add the following code to the head of the html:
<meta charset="UTF-8">
After this setting, all displayed character sets are UTF-8.
Summary:
Although the problem of garbled characters when PHP data is saved to the database is relatively common, in fact, as long as the cause of the problem is understood, it can be easily solved through the above solutions. At the same time, the utf8mb4 character set should be used whenever possible during development.
The above is the detailed content of How to solve the problem of garbled characters when php data is saved to the database. For more information, please follow other related articles on the PHP Chinese website!