Ошибка 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 👍

amelihovv

Когда я парсю вот эту страницу и пытаюсь записать ее контент в базу данных, я получаю следующую ошибку:

SQLSTATE[HY000]: General error: 1366 Incorrect string value: 'xD0 ...' for column 'content'

Collation сначала был utf8_general_ci, потом, как почитал ответы на stackoverflow, поменял на utf8mb4_general_ci, и следом на utf8mb4_unicode_ci, ни одна не помогла.
Что интересно, данная ошибка проявляется только при парсинге этого сайта. Контент сайт отдает в utf8, даже не знаю, в чем тут проблема.


  • Вопрос задан

    более трёх лет назад

  • 40153 просмотра

Пригласить эксперта

Подключение к БД так же нужно изменить на utf8mb4

Проблема в том, что в контенте встречаются символы, которые состоят не из 3 байтов как в UTF-8, а из 4-х (всякие смайлы, эмоджи и пр.), и для их хранения вам надо для поля content использовать SET utf8mb4, а COLLATION utf8mb4_unicode_ci.
Вот тут очень много по этому поводу написано.

UPD: и вторая опция — принудительно очищайте данные до подходящего UTF-8 текста.

Решил ошибку на django так:

Изменил кодировку:
ALTER DATABASE portfolio CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Поставил кодировку в настройке подключения к БД

‘charset’: ‘utf8mb4’,

И заработало после того как прописал такой параметр:
‘init_command’: ‘SET NAMES utf8mb4’,


  • Показать ещё
    Загружается…

24 июн. 2023, в 22:35

1500 руб./за проект

24 июн. 2023, в 21:49

1000 руб./за проект

24 июн. 2023, в 18:21

30000 руб./за проект

Минуточку внимания

При переносе очередного сайта и разворачивание его на 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, и она чудо образом стала работать. Почему до этого выпадала ошибка, для меня осталось загадкой 🙂

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:

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 👍

Содержание

  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.

Источник

  • Ошибка speed too high
  • Ошибка sql 1067 invalid default value for date
  • Ошибка srs b0100 тойота
  • Ошибка srs mercedes ml350
  • Ошибка spn 604 fmi 19 ямз