Меню

Ошибка sql 1366 incorrect string value

UPDATE to the below answer:

The time the question was asked, «UTF8» in MySQL meant utf8mb3. In the meantime, utf8mb4 was added, but to my knowledge MySQLs «UTF8» was not switched to mean utf8mb4.

That means, you’d need to specifically put «utf8mb4», if you mean it (and you should use utf8mb4)

I’ll keep this here instead of just editing the answer, to make clear there is still a difference when saying «UTF8»

Original

I would not suggest Richies answer, because you are screwing up the data inside the database. You would not fix your problem but try to «hide» it and not being able to perform essential database operations with the crapped data.

If you encounter this error either the data you are sending is not UTF-8 encoded, or your connection is not UTF-8. First, verify, that the data source (a file, …) really is UTF-8.

Then, check your database connection, you should do this after connecting:

SET NAMES 'utf8mb4';
SET CHARACTER SET utf8mb4;

Next, verify that the tables where the data is stored have the utf8mb4 character set:

SELECT
  `tables`.`TABLE_NAME`,
  `collations`.`character_set_name`
FROM
  `information_schema`.`TABLES` AS `tables`,
  `information_schema`.`COLLATION_CHARACTER_SET_APPLICABILITY` AS `collations`
WHERE
  `tables`.`table_schema` = DATABASE()
  AND `collations`.`collation_name` = `tables`.`table_collation`
;

Last, check your database settings:

mysql> show variables like '%colla%';
mysql> show variables like '%charac%';

If source, transport and destination are utf8mb4, your problem is gone;)

When you try to insert a new record into your MySQL database table, you may encounter an error saying Incorrect string value along with some UTF-8 hex code for the description.

For example, suppose you create a Test table with only one column as follows:

CREATE TABLE `Test` (
  `names` varchar(255)
) 

Next, let’s insert the following Egyptian hieroglyph character into the table:

INSERT INTO Test VALUES('𓀀');

Your MySQL server may respond with the following error:

ERROR 1366 (HY000): 
Incorrect string value: 'xF0x93x80x80' for column 'names' at row 1

The error above is because the character 𓀀 requires 4-bytes to be represented in UTF-8 encoding.

By default, MySQL databases and tables are created using a UTF-8 with 3-bytes encoding. You can see the encoding used for your table by using the SHOW CREATE TABLE statement as follows:

SHOW CREATE TABLE Test G

Here’s the result from my computer:

*************************** 1. row ***************************
       Table: Test
Create Table: CREATE TABLE `Test` (
  `names` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3

As you can see, the table uses the DEFAULT CHARSET=utf8mb3 and the names column uses CHARACTER SET utf8.

The MySQL utf8 or utf8mb3 can’t store string values that contain a UTF-8 4-bytes character.

To store the values, you need to use the utf8mb4 character set.

Here’s the query to alter your database, table, or column to utf8mb4 character set:

-- Change a database
ALTER DATABASE [database_name] 
  CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci; 

-- Change a table
ALTER TABLE [table_name] 
  CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; 

-- Change a column
ALTER TABLE [table_name] 
  CHANGE [column_name] [column_name] VARCHAR(255) 
  CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

When you change the character set on the database level, then any new table you create for that database in the future will use that character set as the default encoding.

Returning to the Test table, you can alter just the names column to make the INSERT statement works:

ALTER TABLE `Test`
  CHANGE `names` `names` VARCHAR(255) 
  CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Now you should be able to insert the character 𓁴 into the table:

INSERT INTO Test VALUES('𓁴');
-- Query OK, 1 row affected (0.00 sec)

By default, MySQL version 8 should use utf8mb4 encoding and collation for your databases. If you see utf8 or utf8mb3, then you might be using MySQL version below 8 (MySQL version 5 may default to utf8mb3).

When you encounter this error, pay attention to the characters that you want to insert into the database.

They may look like normal characters, but if you copy and paste them from some source, then they may have a strange encoding attached to them.

For example, the GOTHIC LETTER SAUIL 𐍃 looks like a normal capital S but actually a 4-bytes character:

INSERT INTO Test VALUES('𐍃');

ERROR 1366 (HY000): 
Incorrect string value: 'xF0x90x8Dx83' for column 'names' at row 1

Alternatively, you can also pass the hex code (xF0x90x8Dx83 in the example above) into Google to look for the exact character that causes the error.

To conclude, the ERROR 1366: Incorrect string value happens when MySQL can’t insert the value you specified into the table because of incompatible encoding.

You need to modify or remove characters that have 4-bytes UTF-8 encoding, or you can change the encoding and collation used by MySQL.

Note that utf8 in MySQL always refers to utf8mb3.

To use the 4-bytes UTF-8 encoding, it needs to be specified as utf8mb4.

With this information, you should now be able to resolve this error. Feel free to use the provided ALTER statements above if you need it 👍

I am facing issues with my table structure :

My_Table_Name1

CREATE TABLE `My_Table_Name1` (
  `twitter_id_str` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `twitter_screen_name` varchar(512) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  UNIQUE KEY `twitter_id_str` (`twitter_id_str`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci 

For database I also have same charset and collation:

CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

I’m trying to insert an emoji into this table:

insert into My_Table_Name1 values("2","😀") 

However, I get an error:

Error Code: 1366. Incorrect string value: ‘xF0x9Fx98x80’ for column ‘twitter_screen_name’ at row 1 0.00027 sec

How to solve this?

Thanks in advance.

dbdemon's user avatar

dbdemon

5,9264 gold badges17 silver badges36 bronze badges

asked May 11, 2018 at 11:51

RAJ KASHWAN's user avatar

5

The problem appears to be in the Client.

When the client connects to the MySQL server, it needs to announce that the bytes in the client are utf8mb4. This can be done in several ways:

  • In the connection parameters (client-dependent).
  • SET NAMES utf8mb4.

U+1F600 is the Unicode representation for that Emoji.
xF0x9Fx98x80 is the equivalent Hex.
F09F9880 is the UTF-8 (utf8mb4) in Hex.

Avoid the Unicode representation.

answered May 24, 2018 at 23:28

Rick James's user avatar

Rick JamesRick James

72.7k4 gold badges41 silver badges101 bronze badges

This seems like a problem with mysql-workbench (tested with version 6.3.9 on Fedora and MySQL 5.7 (CentOS)) where emojis are not converted to the correct unicode.

In the command-line mysql client the emojis get converted to codes when they’re pasted in, so the query

INSERT INTO My_Table_Name1 values("2","😀"); 

becomes:

INSERT INTO My_Table_Name1 values("4","U+1F600");

which works fine.

However, in mysql-workbench, the emoji is not converted as you paste it in, and the query result is:

Error Code: 1366. Incorrect string value: ‘xF0x9Fx98x80’ for column ‘twitter_screen_name’ at row 1

answered May 12, 2018 at 16:28

dbdemon's user avatar

dbdemondbdemon

5,9264 gold badges17 silver badges36 bronze badges

При переносе очередного сайта и разворачивание его на VDS-ке, у меня появилась ошибка:

MySQL Query Error: [[1366] Incorrect string value: ‘xB1NxC30x10xFD…’ for column ‘COOKIES’ at row 1]

Она была связана с тем, что не получалось сохраненить в БД куки из-за того что кодировка из скрипта не совпадала с кодировкой в БД.

Что бы это исправить, необходимо сменить кодировку в БД и определить эту кодировку в скриптах битрикса для подключения с базой данных. Т.к. ошибка может возникать из-за того, что пытается записать в БД символы, которые состоят не из 3 байтов, как в UTF-8, а из 4-х, то для хранения поля необходимо использовать utf8mb4. Поменять кодировку можно с помощью скрипта php:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<?php

$dbName = ‘YOUR_DB_NAME’;

$user = ‘YOUR_USER_NAME’;

$password = ‘YOUR_PASSWORD’;

$dsn = ‘mysql:dbname=’.$dbName.‘;host=localhost’;

$time_n=time();

try {

    $dbh = new PDO($dsn, $user, $password);

} catch (PDOException $e) {

    exit(‘Подключение не удалось: ‘ . $e->getMessage());

}

$sql = «SELECT distinct CONCAT( ‘alter table ‘, TABLE_SCHEMA, ‘.’, TABLE_NAME, ‘ CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;’ ) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ‘$dbName’;»;

$arErrors = [];

$cnt = 0;

foreach ($dbh->query($sql) as $row) {

    try {

        $dbh->exec($row[0]);

    } catch (PDOException $e) {

        $arErrors[] = ‘Ошибка: ‘ . $e->getMessage();

    }

    $cnt++;

}

$time_k=time();

echo ‘Затронуто таблиц: ‘ . $cnt . ‘ Из них с ошибками: ‘ . count($arErrors) . ‘<br>’;

echo ‘Время выполнения: ‘ . strftime(‘%M:%S’,$time_k$time_n) . ‘<br>’;

if (count($arErrors) > 0) {

    echo ‘Список ошибок: <br>’;

    echo ‘<pre>’;

    print_r($arErrors);

    echo ‘</pre>’;

}

Результат выполнения скрипта:

Затем в конфигах битрикса прописать:
— в файле bitrix/php_interface/after_connect_d7.php:

$connection = BitrixMainApplication::getConnection();

$connection->queryExecute(«SET NAMES ‘utf8′»);

$connection->queryExecute(‘SET collation_connection = «utf8mb4_unicode_ci»‘);

— в файле bitrix/php_interface/after_connect.php:

$DB->Query(«SET NAMES ‘utf8′»);

$DB->Query(‘SET collation_connection = «utf8mb4_unicode_ci»‘);

После, если система заработает, следеут сделать проверку системы:

Bitrix проверка системы
Если будут ошибки, то исправить их следуя подсказкам битрикса.

Если же ошибка не исправилась, значит необходимо поиграться с вариантами кодировки. В моем случае эти действия помогли, но не с первого раза. По итогу оставил кодировку utf8 и utf8_unicode_ci, и она чудо образом стала работать. Почему до этого выпадала ошибка, для меня осталось загадкой 🙂

What happened:

While rsync from local disk to juicefs mount, it suddenly (after several hours) stopped with

Failed to sync with 11 errors: last error was: open /mnt/juicefs/folder/file.xls: input/output error

On the jfs log, i can find these:

juicefs[187516] <ERROR>: error: Error 1366: Incorrect string value: 'xE9sa sa...' for column `jfsdata`.`jfs_edge`.`name` at row 1
goroutine 43510381 [running]:
runtime/debug.Stack()
        /usr/local/go/src/runtime/debug/stack.go:24 +0x65
github.com/juicedata/juicefs/pkg/meta.errno({0x2df8860, 0xc0251d34a0})
        /go/src/github.com/juicedata/juicefs/pkg/meta/utils.go:76 +0xc5
github.com/juicedata/juicefs/pkg/meta.(*dbMeta).doMknod(0xc0000e0c40, {0x7fca7e165300, 0xc00ed28040}, 0x399f6f, {0xc025268160, 0x1f}, 0x1, 0x1b4, 0x0, 0x0, ...)
        /go/src/github.com/juicedata/juicefs/pkg/meta/sql.go:1043 +0x29e
github.com/juicedata/juicefs/pkg/meta.(*baseMeta).Mknod(0xc0000e0c40, {0x7fca7e165300, 0xc00ed28040}, 0x399f6f, {0xc025268160, 0x1f}, 0xc0, 0x7b66, 0x7fca, 0x0, ...)
        /go/src/github.com/juicedata/juicefs/pkg/meta/base.go:594 +0x275
github.com/juicedata/juicefs/pkg/meta.(*baseMeta).Create(0xc0000e0c40, {0x7fca7e165300, 0xc00ed28040}, 0x26b5620, {0xc025268160, 0x2847500}, 0x8040, 0xed2, 0x8241, 0xc025267828, ...)
        /go/src/github.com/juicedata/juicefs/pkg/meta/base.go:601 +0x109
github.com/juicedata/juicefs/pkg/vfs.(*VFS).Create(0xc000140640, {0x2e90348, 0xc00ed28040}, 0x399f6f, {0xc025268160, 0x1f}, 0x81b4, 0x22a4, 0xc0)
        /go/src/github.com/juicedata/juicefs/pkg/vfs/vfs.go:357 +0x256
github.com/juicedata/juicefs/pkg/fuse.(*fileSystem).Create(0xc000153900, 0xc024980101, 0xc022a48a98, {0xc025268160, 0x1f}, 0xc022a48a08)
        /go/src/github.com/juicedata/juicefs/pkg/fuse/fuse.go:221 +0xcd
github.com/hanwen/go-fuse/v2/fuse.doCreate(0xc022a48900, 0xc022a48900)
        /go/pkg/mod/github.com/juicedata/go-fuse/v2@v2.1.1-0.20210926080226-cfe1ec802a7f/fuse/opcode.go:163 +0x68
github.com/hanwen/go-fuse/v2/fuse.(*Server).handleRequest(0xc00179c000, 0xc022a48900)
        /go/pkg/mod/github.com/juicedata/go-fuse/v2@v2.1.1-0.20210926080226-cfe1ec802a7f/fuse/server.go:483 +0x1f3
github.com/hanwen/go-fuse/v2/fuse.(*Server).loop(0xc00179c000, 0x20)
        /go/pkg/mod/github.com/juicedata/go-fuse/v2@v2.1.1-0.20210926080226-cfe1ec802a7f/fuse/server.go:456 +0x110
created by github.com/hanwen/go-fuse/v2/fuse.(*Server).readRequest
        /go/pkg/mod/github.com/juicedata/go-fuse/v2@v2.1.1-0.20210926080226-cfe1ec802a7f/fuse/server.go:323 +0x534
 [utils.go:76]

Nothing was logged at MariaDB side.

Environment:

  • juicefs version 1.0.0-beta2+2022-03-04T03:00:41Z.9e26080
  • Ubuntu 20.04
  • MariaDB 10.4

Содержание

  1. #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  2. Сообщения 15
  3. 1 Тема от aler 2009-12-14 00:26:28
  4. Тема: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  5. 2 Ответ от Hanut 2009-12-14 00:51:26
  6. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  7. 3 Ответ от aler 2009-12-14 09:57:04 (изменено: aler, 2009-12-14 10:00:09)
  8. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  9. 4 Ответ от Hanut 2009-12-14 12:14:01
  10. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  11. 5 Ответ от aler 2009-12-14 14:51:45
  12. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  13. 6 Ответ от Hanut 2009-12-14 22:31:13
  14. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  15. 7 Ответ от aler 2009-12-15 01:44:41
  16. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  17. 8 Ответ от Hanut 2009-12-15 13:13:45
  18. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  19. 9 Ответ от aler 2009-12-15 14:18:28
  20. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  21. 10 Ответ от aler 2009-12-21 22:12:58
  22. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  23. 11 Ответ от Hanut 2009-12-22 00:10:45
  24. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  25. 12 Ответ от aler 2009-12-22 00:15:15
  26. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  27. 13 Ответ от Hanut 2009-12-22 12:07:00
  28. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  29. 14 Ответ от Hanut 2010-05-20 11:56:07
  30. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  31. 15 Ответ от alex252003 2010-05-20 12:08:13
  32. Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In
  33. MySQL — How to fix the ‘Incorrect string value’ error
  34. Level up your programming skills
  35. About

#1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

Форум PHP-MyAdmin.RU → MySQL & phpMyAdmin → #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

Чтобы отправить ответ, вы должны войти или зарегистрироваться

Сообщения 15

1 Тема от aler 2009-12-14 00:26:28

  • aler
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-12-13
  • Сообщений: 7

Тема: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

Уважаемые форумчане, ОЧЕНЬ СРОЧНО НУЖНА ВАША ПОМОЩЬ.
При добавлении данных в таблицу выдает ошибку (#1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In)
Как ее решить.
вот таблица:
Поле Тип Ноль По умолчанию Допольнительно
id int(4) Да NULL auto_increment
title varchar(255) Да NULL
description text Да NULL
text text Да NULL
date date Да 000-00-00
author varchar(255) Да NULL

а вот запрос на добавление инфи:

mysql_query(«INSERT INTO news (title,description,text,date,author) VALUE (‘$title’,’$description’,’$text’,’$date’,’$author’)»);

2 Ответ от Hanut 2009-12-14 00:51:26

  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,722

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

aler
В таблице уберите у поля id значение по умолчанию. В поле «Ноль» должно быть «нет», в поле «По умолчанию» — тоже «нет». Так же поле id должно быть первичным ключом (проверьте индекс).

3 Ответ от aler 2009-12-14 09:57:04 (изменено: aler, 2009-12-14 10:00:09)

  • aler
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-12-13
  • Сообщений: 7

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

aler
В таблице уберите у поля id значение по умолчанию. В поле «Ноль» должно быть «нет», в поле «По умолчанию» — тоже «нет». Так же поле id должно быть первичным ключом (проверьте индекс).

я сам над этим думал. НО! при создании таблицы я все значения ставлю NOT NULL и в самой структуре таблицы после создания тоже стоят эти значения. А после того как просматриваешь свойства таблици все значения становятся в NULL. Сколько раз не пробовал поменять все равно тоже самое.
id у меня является первичным ключом. Может это глюк самого phpmyadmina или mysql?
И еще, когда вручную указываешь id все данные занюсятся в таблицу.

4 Ответ от Hanut 2009-12-14 12:14:01

  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,722

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

aler
Попробуйте найти конфигурационный файл MySQL (my.ini./my.cnf) и поправить в нем строку (если она выглядит иначе):
sql-mode=»STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION»

5 Ответ от aler 2009-12-14 14:51:45

  • aler
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-12-13
  • Сообщений: 7

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

aler
Попробуйте найти конфигурационный файл MySQL (my.ini./my.cnf) и поправить в нем строку (если она выглядит иначе):
sql-mode=»STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION»

в своем MySQL нашел файл my.cnf но там вообще такой строки нету.
Кстате auto_increment начинает работать когда добавишь пару записей вручную с указанием id. После этого спокойно добавляет с формы.
Ничего не могу понять.

6 Ответ от Hanut 2009-12-14 22:31:13

  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,722

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

Попробуйте добавить эту строку в my.cnf, в раздел [mysqld].

Не должно быть, чтобы без выставления NULL оно добавлялось автоматически.

7 Ответ от aler 2009-12-15 01:44:41

  • aler
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-12-13
  • Сообщений: 7

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

Попробуйте добавить эту строку в my.cnf, в раздел [mysqld].

Не должно быть, чтобы без выставления NULL оно добавлялось автоматически.

Вставил эту строчку куда вы сказали. Никаких изменений.

И еще один вопросик: Какую кодировку использовать когда добавляешь данные на русском или украинском языке? а то в базе отображаются знаки вопроса (. )

8 Ответ от Hanut 2009-12-15 13:13:45

  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,722

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

aler
Кодировка в БД зависит от кодировки страниц сайта: если сайт в windows-1251, то таблицы должны иметь сравнение cp1251_general_ci; если в utf-8, то utf8_general_ci.

Если вы сами пишите скрипт вставки данных, то обязательно сразу после функции mysql_connect добавьте строку определяющую кодировку соединения с MySQL:

9 Ответ от aler 2009-12-15 14:18:28

  • aler
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-12-13
  • Сообщений: 7

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

aler
Кодировка в БД зависит от кодировки страниц сайта: если сайт в windows-1251, то таблицы должны иметь сравнение cp1251_general_ci; если в utf-8, то utf8_general_ci.

Если вы сами пишите скрипт вставки данных, то обязательно сразу после функции mysql_connect добавьте строку определяющую кодировку соединения с MySQL:

Большое спасибо. вот это мне и нужно было.

10 Ответ от aler 2009-12-21 22:12:58

  • aler
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-12-13
  • Сообщений: 7

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

Все равно ничего не пойму, почему id не ставится автоматически. и как не крутил NULL ставится само по себе.

11 Ответ от Hanut 2009-12-22 00:10:45

  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,722

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

aler
Скопируйте сюда структуру таблицы. Пока у меня нет идей почему так получается.

12 Ответ от aler 2009-12-22 00:15:15

  • aler
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-12-13
  • Сообщений: 7

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

aler
Скопируйте сюда структуру таблицы. Пока у меня нет идей почему так получается.

Поле Тип Сравнение Атрибуты Ноль По умолчанию Дополнительно
id int(4) Да NULL auto_increment
login varchar(20) Да NULL
password varchar(20) Да NULL

вот такая структура.

13 Ответ от Hanut 2009-12-22 12:07:00

  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,722

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

aler
Я имел в виду структуру в виде SQL запроса. Увидеть ее можно если выбрать таблицу, затем перейти на страницу экспорта, там убрать галочку в блоке данных и не выставлять галочку сохранения в файл. Тогда структура будет выведена прямо в phpMyAdmin.

14 Ответ от Hanut 2010-05-20 11:56:07

  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,722

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

alex252003
Строка
SET SQL_MODE=»NO_AUTO_VALUE_ON_ZERO»;
Будет в дампе всегда, это необходимо для корректной вставки значений в поле имеющее параметр автоувеличения (AUTO_INCREMENT).

Влияет режим NO_AUTO_VALUE_ON_ZERO только на те значения, которые для поля id будут нулем. Если в дампе есть такие значения, значит будет выводиться ошибка.

В крайнем случае, можете перед импортом дампа закомментировать строку таким образом:
— SET SQL_MODE=»NO_AUTO_VALUE_ON_ZERO»;

15 Ответ от alex252003 2010-05-20 12:08:13

  • alex252003
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2010-05-20
  • Сообщений: 2

Re: #1366 — Incorrect integer value: » for column ‘id’ at row 1#1366 — In

alex252003
Строка
SET SQL_MODE=»NO_AUTO_VALUE_ON_ZERO»;
Будет в дампе всегда, это необходимо для корректной вставки значений в поле имеющее параметр автоувеличения (AUTO_INCREMENT).

Влияет режим NO_AUTO_VALUE_ON_ZERO только на те значения, которые для поля id будут нулем. Если в дампе есть такие значения, значит будет выводиться ошибка.

В крайнем случае, можете перед импортом дампа закомментировать строку таким образом:
— SET SQL_MODE=»NO_AUTO_VALUE_ON_ZERO»;

спасибо уже разобрался, окзалось дело в кодировке, я поставил в файле my.ini кодировку:
default-character-set=cp1251
и в таблице поставил сравнение cp1251_general_ci
и все заработало

зы я свое сообщение удалил а потом только увидел что вы уже ответили

Источник

MySQL — How to fix the ‘Incorrect string value’ error

Posted on Dec 15, 2021

When you try to insert a new record into your MySQL database table, you may encounter an error saying Incorrect string value along with some UTF-8 hex code for the description.

For example, suppose you create a Test table with only one column as follows:

Next, let’s insert the following Egyptian hieroglyph character into the table:

Your MySQL server may respond with the following error:

The error above is because the character 𓀀 requires 4-bytes to be represented in UTF-8 encoding.

By default, MySQL databases and tables are created using a UTF-8 with 3-bytes encoding. You can see the encoding used for your table by using the SHOW CREATE TABLE statement as follows:

Here’s the result from my computer:

As you can see, the table uses the DEFAULT CHARSET=utf8mb3 and the names column uses CHARACTER SET utf8 .

The MySQL utf8 or utf8mb3 can’t store string values that contain a UTF-8 4-bytes character.

To store the values, you need to use the utf8mb4 character set.

Here’s the query to alter your database, table, or column to utf8mb4 character set:

When you change the character set on the database level, then any new table you create for that database in the future will use that character set as the default encoding.

Returning to the Test table, you can alter just the names column to make the INSERT statement works:

Now you should be able to insert the character 𓁴 into the table:

By default, MySQL version 8 should use utf8mb4 encoding and collation for your databases. If you see utf8 or utf8mb3 , then you might be using MySQL version below 8 (MySQL version 5 may default to utf8mb3 ).

When you encounter this error, pay attention to the characters that you want to insert into the database.

They may look like normal characters, but if you copy and paste them from some source, then they may have a strange encoding attached to them.

For example, the GOTHIC LETTER SAUIL 𐍃 looks like a normal capital S but actually a 4-bytes character:

Alternatively, you can also pass the hex code ( xF0x90x8Dx83 in the example above) into Google to look for the exact character that causes the error.

To conclude, the ERROR 1366: Incorrect string value happens when MySQL can’t insert the value you specified into the table because of incompatible encoding.

You need to modify or remove characters that have 4-bytes UTF-8 encoding, or you can change the encoding and collation used by MySQL.

Note that utf8 in MySQL always refers to utf8mb3 .

To use the 4-bytes UTF-8 encoding, it needs to be specified as utf8mb4 .

With this information, you should now be able to resolve this error. Feel free to use the provided ALTER statements above if you need it 👍

Level up your programming skills

I’m sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Nathan Sebhastian is a software engineer with a passion for writing tech tutorials.
Learn JavaScript and other web development technology concepts through easy-to-understand explanations written in plain English.

Источник

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка sql 1062 duplicate entry 1 for key primary
  • Ошибка srs mercedes sprinter