嘗試將中文字元插入 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中文網其他相關文章!