萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

MySQL 儲存 Emoji/特殊字元報錯 1366 Incorrect string value 解決方案

錯誤現象

Incorrect string value: '\xF0\x9F\x98\x8A\xF0\x9F...' for column 'xxx' at row 1

原因:資料庫/表/欄位字元集為 utf8(實為 utf8mb3,僅支援 3 位元組字元),無法儲存 4 位元組的 Emoji(😊 = F0 9F 98 8A)或生僻字。

徹底解決:升級至 utf8mb4

1. 修改資料庫預設字元集

ALTER DATABASE db_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

2. 修改表預設字元集

ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

3. 修改欄位字元集(如僅部分欄位需支援)

ALTER TABLE table_name MODIFY column_name VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

4. 連線層指定字元集(關鍵)

  • PHP PDO:new PDO('mysql:host=...;dbname=...;charset=utf8mb4', ...)
  • PHP mysqli:$mysqli->set_charset('utf8mb4');
  • JDBC URL:jdbc:mysql://...?characterEncoding=utf8mb4
  • Python PyMySQL:charset='utf8mb4'

5. my.cnf 統一預設(可選)

[client]
default-character-set = utf8mb4

[mysql]
default-character-set = utf8mb4

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
init_connect = 'SET NAMES utf8mb4'

快速臨時方案(不改結構):PHP 端過濾/轉碼

// 過濾掉 4 位元組字元
$str = preg_replace('/[\xF0-\xF7][\x80-\xBF]{3}/', '', $str);

// 或轉為 HTML 實體儲存
$str = mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8');

缺點:資料遺失或讀取需反轉,不推薦長期使用。

驗證

SHOW VARIABLES LIKE 'character_set%';
SHOW CREATE TABLE table_name\G;
INSERT INTO t(col) VALUES ('😊🎉');
SELECT col, HEX(col) FROM t;
copyright © 萬盛學電腦網 all rights reserved