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.
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;
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"
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");
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!