尝试将中文字符插入 MySQL 数据库时,您可能会因字符集编码不匹配而遇到困难。要解决此问题,请按照以下步骤操作:
创建数据库表时,指定字符集为 UTF-8:
<code class="sql">CREATE TABLE table_name ( ... ) CHARACTER SET = utf8;</code>
向表中插入汉字时,指定字段的字符集为UTF-8:
<code class="sql">ALTER TABLE table_name MODIFY COLUMN field_name VARCHAR(255) CHARACTER SET utf8;</code>
<code class="sql">ALTER DATABASE dbname CHARACTER SET = utf8; ALTER TABLE table_name DEFAULT CHARACTER SET = utf8;</code>
<code class="sql">SET CHARACTER SET utf8;</code>
<code class="sql">SET NAMES 'utf8';</code>
<code class="php">mysql_set_charset('utf8', $link);</code>
相关文章:
其他资源:
以下是演示如何解决问题的详细代码示例:
<code class="php"><?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "test"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Set connection character set to UTF-8 $conn->set_charset("utf8"); // Create database and table with UTF-8 encoding $conn->query("CREATE DATABASE IF NOT EXISTS mydb CHARACTER SET utf8"); $conn->query("CREATE TABLE IF NOT EXISTS mydb.mytable (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) CHARACTER SET utf8)"); // Insert Chinese characters into the table $sql = "INSERT INTO mydb.mytable (name) VALUES (?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("s", $name); $name = "你好"; $stmt->execute(); // Close connection $stmt->close(); $conn->close(); ?></code>
以上是如何解决MySQL插入汉字问题?的详细内容。更多信息请关注PHP中文网其他相关文章!