Home  >  Article  >  Backend Development  >  What to do if php Chinese save database is garbled

What to do if php Chinese save database is garbled

PHPz
PHPzOriginal
2023-04-10 09:35:46541browse

In PHP, if Chinese characters are used to save to the database, garbled characters may appear. This is because the database and web page encoding are inconsistent, causing the data to be stored incorrectly. Here are some solutions.

  1. Database encoding settings

First confirm whether the encoding of the database is UTF-8 (or other encodings that support Chinese). If not, you can set the encoding in the database to UTF-8.

If you use a MySQL database, you need to specify the encoding when creating the database and data table:

CREATE DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE TABLE tablename (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
    age INT(3)
) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  1. PHP encoding settings

Secondly, in the PHP script Set the encoding to UTF-8:

header('Content-Type: text/html; charset=utf-8');

You can also set it in the PHP configuration file php.ini:

default_charset = "utf-8"
  1. Database connection settings

In When connecting to the database, you also need to set the encoding to UTF-8. If you use PDO to connect to the database, you can write like this:

$dsn = "mysql:host=localhost;dbname=dbname;charset=utf8mb4";
$dbh = new PDO($dsn, $user, $password);

If you use MySQLi to connect to the database, you can write like this:

$mysqli = new mysqli("localhost", "user", "password", "dbname");
mysqli_set_charset($mysqli, "utf8mb4");
  1. Data encoding conversion

If If none of the above methods can solve the problem, it may be that the string encoding saved to the database is inconsistent with the database encoding, and encoding conversion is required. Conversion can be done using PHP's iconv function or mb_convert_encoding function.

$str = "你好";
$str = iconv('gbk', 'utf-8', $str);
//或
$str = mb_convert_encoding($str, 'utf-8', 'gbk');

Summary

When saving Chinese characters to the database in PHP, make sure that the encoding of the database and the web page are consistent, and set the encoding to UTF-8 when connecting to the database and the PHP script. If garbled characters appear, try encoding conversion. Hope these methods can help you solve the problem.

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

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