Current Location: Home> Latest Articles> Complete Guide and Practical Tips for Inserting Chinese Characters in PHP

Complete Guide and Practical Tips for Inserting Chinese Characters in PHP

gitbox 2025-08-08

Key Techniques for Inserting Chinese Characters

In PHP development, properly inserting and handling Chinese characters is crucial. To avoid garbled text issues, understanding and correctly setting character encoding, especially UTF-8, is essential. This article explains how to insert Chinese characters smoothly in PHP, combined with best practices for security.

Understanding the Importance of Character Encoding

The first step in handling Chinese characters is to confirm the encoding format. UTF-8 is the most widely used and compatible encoding. It is recommended to ensure that your web pages, PHP files, and databases all use UTF-8 encoding to fundamentally prevent garbled characters.

Setting the Database Connection Encoding

When connecting to the database using PHP, it’s necessary to set the connection charset to UTF-8 first to ensure Chinese characters are stored and retrieved correctly. Example code:

$mysqli = new mysqli("localhost", "username", "password", "database");
$mysqli->set_charset("utf8");

Example of Inserting Chinese Characters Using PHP

After confirming encoding settings, you can insert Chinese characters into the database with PHP. Here is an example:

$sql = "INSERT INTO table_name (column_name) VALUES ('中文字符')";
if ($mysqli->query($sql) === TRUE) {
    echo "New record inserted successfully";
} else {
    echo "Error: " . $sql . " " . $mysqli->error;
}

Security Practice: Preventing SQL Injection

To ensure database security, it’s recommended to use prepared statements when inserting Chinese characters. This effectively prevents SQL injection attacks. The following example shows how to safely insert Chinese using PDO:

$pdo = new PDO("mysql:host=localhost;dbname=database;charset=utf8", "username", "password");
$stmt = $pdo->prepare("INSERT INTO table_name (column_name) VALUES (:chinese_character)");
$stmt->execute(['chinese_character' => '中文字符']);

Ensure Correct Output Encoding

After inserting Chinese characters, the web page display must also use the correct encoding. It’s recommended to add the following Meta tag in the HTML head to specify UTF-8 encoding:

<span class="fun"><meta charset="UTF-8"></span>

Conclusion

The key to inserting Chinese characters in PHP is to consistently use UTF-8 encoding, from database connections to page output. Meanwhile, using prepared statements not only improves security but also ensures correct insertion of Chinese data. Mastering these methods will effectively prevent garbled text and security risks, making your PHP applications more stable and secure.