MySQL HY000 1366:尝试存储4字节的utf8字符

时间:2018-02-24 17:57:17

标签: php mysql encoding character-encoding

我过去曾经遇到过这个问题,原因是解决方案是使用utf8mb4字符集,因为在mysql utf8中不支持4字节长字符。我的领域:

CREATE TABLE `messages` (
  ...
  `body` text CHARACTER SET utf8mb4,
  ...
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

然后我尝试插入此字符“”,然后我

  

SQLSTATE [HY000]:常规错误:1366字符串值不正确:第1行第'body'列的'\ xF0 \ x9F \ x98 \ x82'

我正在使用PHP PDO并在DSN中指定charset=utf8mb4,但我甚至尝试通过使用客户端连接MySQL直接插入它,但我仍然遇到错误。我错过了什么?

这是我的PHP代码设置我的连接

$charset = 'utf8mb4';
...
$pdo = new PDO("mysql:host={$host};dbname={$dbname};charset={$charset};", $user, $pass, [
      PDO::ATTR_EMULATE_PREPARES => false,
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
      PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4'
]);

在@ sorak的答案中添加了设置,SHOW VARIABLES LIKE 'char%'的输出:

character_set_connection    utf8mb4
character_set_database  utf8mb4
character_set_filesystem    binary
character_set_results   utf8mb4
character_set_server    utf8mb4
character_set_system    utf8
character_sets_dir  /usr/share/mysql/charsets/

1 个答案:

答案 0 :(得分:0)

可在此处找到可能的答案:https://dba.stackexchange.com/questions/89355/unable-to-insert-utf8mb4-characters-in-mysql-5-6

基本上,请确保您在my.cnf中指定了字符集定义:

[client]
default-character-set=utf8mb4

[mysqld]
character-set-server = utf8mb4

[mysql]
default-character-set=utf8mb4

然后重启服务:service mysql restart