Home >Database >Mysql Tutorial >How to Successfully Insert Chinese Characters into a MySQL Database?

How to Successfully Insert Chinese Characters into a MySQL Database?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 00:52:28628browse

How to Successfully Insert Chinese Characters into a MySQL Database?

Character Encoding Issue in MySQL: Inserting Chinese Characters

When attempting to store Chinese characters in MySQL, users may encounter difficulties due to character encoding issues. One such issue arises when the input is encoded using Big5 but the MySQL table is configured with a different encoding. This can result in incorrect insertion or display of Chinese characters.

Solution:

To resolve this problem, it is necessary to ensure that the following settings are correctly configured:

  • Table Character Set: Create the MySQL table using the UTF-8 character set, which can accommodate Chinese characters.
  • Connection Character Set: Set the PHP MySQL connection to UTF-8 before executing any SQL queries. This ensures that data is transmitted between PHP and MySQL using the correct encoding.

Detailed Steps:

<code class="sql">create table chinese_table (id int, chinese_column varchar(255) CHARACTER SET utf8);</code>
<code class="php"><?php
// Set MySQL connection to UTF-8
mysql_query("SET character_set_client=utf8");
mysql_query("SET character_set_connection=utf8");

// Insert Chinese characters into the database
$chinese_value = $_POST['chinese_value'];
$query = "INSERT INTO chinese_table (chinese_column) VALUES ('" . mysql_real_escape_string($chinese_value) . "')";
mysql_query($query);
?></code>

Example:

The following PHP code demonstrates how to insert Chinese characters into a MySQL table with UTF-8 encoding:

<code class="php"><?php

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database_name");
$mysqli->set_charset("utf8");

// Set the input Chinese value
$chineseValue = "中文";

// Create an SQL query to insert the value into the table
$sql = "INSERT INTO chinese_table (chinese_column) VALUES (?)";

// Prepare the statement and bind the Chinese value
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $chineseValue);

// Execute the statement
$stmt->execute();

// Close the statement and the connection
$stmt->close();
$mysqli->close();

?></code>

By taking these steps, the Chinese characters will be properly encoded and inserted into the MySQL table.

The above is the detailed content of How to Successfully Insert Chinese Characters into a MySQL Database?. 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