Resolving the Issue of Inserting Chinese Characters into MySQL
Inserting Chinese characters into MySQL can be problematic if the database or table is not configured to handle Unicode data. This issue commonly arises when cookies are encoded using the big5 character set.
Solution:
To resolve this issue, it is crucial to ensure that the database and table are set up with UTF-8 character encoding. Here's how to implement this:
1. Configuring the Database for UTF-8:
Use the character set argument when creating the database:
<code class="sql">create database stackoverflow CHARACTER SET utf8;</code>
This sets the default character set for the database to UTF-8.
2. Configuring the Table for UTF-8:
When creating the table, specify the character set for each field:
<code class="sql">create table attendance_count ( username varchar(30) CHARACTER SET utf8, date date, count_time int, appendix varchar(200) CHARACTER SET utf8 );</code>
This ensures that the fields handling Chinese characters, specifically the appendix field in this case, are set to UTF-8 encoding.
3. Inserting Data with UTF-8 Encoding:
When executing the insert query, explicitly set the character set:
<code class="sql">mysql_query("SET CHARACTER SET utf8;"); mysql_query($sql2);</code>
This specifies that the data being inserted should be treated as UTF-8 encoded.
4. Additional Considerations:
Detailed Code Example:
The following code demonstrates these principles:
<code class="php">$db = new mysqli("localhost", "username", "password", "dbname"); // Set character set for the connection $db->set_charset("utf8"); $sql = "INSERT INTO attendance_count (username, date, count_time, appendix) VALUES (?, ?, ?, ?)"; $stmt = $db->prepare($sql); // Bind parameters in UTF-8 encoding $stmt->bind_param("ssis", $username, $date, $count_time, $appendix); // Execute the query $stmt->execute(); $stmt->close(); $db->close();</code>
By following these steps, you should be able to successfully insert Chinese characters into your MySQL database.
The above is the detailed content of How to Properly Insert Chinese Characters into MySQL?. For more information, please follow other related articles on the PHP Chinese website!