I can’t resolve my problem, this is the error from mysql that I’m getting:
I can edit and update my data when I’ve got one record in the database but when I add two rows, I get the error.
Some pictures from database
And when I change the row, row ID goes down to 0 and that’s is a problem as I can’t edit other rows.
CREATE TABLE `dati` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`value1` varchar(255) NOT NULL,
`value2` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1 PACK_KEYS=1
Update Code:
<?php // Izlabot datus datubāzē!
$titletxt = $_POST['title_edit'];
$value1 = $_POST['value1_edit'];
$value2 = $_POST['value2_edit'];
if(isset($_POST['edit'])){
$con=mysqli_connect("localhost","root","","dbname");
if (mysqli_connect_errno())
{
echo "Neizdevās savienoties ar MySQL: " . mysqli_connect_error();
}
$sql="UPDATE dati SET ID='$ID',title= '$titletxt',value1='$value1',value2='$value2' WHERE 1";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo '<script>
alert(" Ieraksts ir veiksmīgi labots! ");
window.location.href = "index.php";
</script>';
mysqli_close($con);
}
?>
From form:
<?php
$con=mysqli_connect("localhost","root","","dbname");
if (mysqli_connect_errno())
{
echo "Neizdevās savienoties ar MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM dati");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><input id='titled' type='text' name='title_edit' value='" . $row['title'] . "'></td>";
echo "<td><input id='value1d' type='text' name='value1_edit' value='" . $row['value1'] . "'></td>";
echo "<td><input id='value2d' type='text' name='value2_edit' value='" . $row['value2'] . "'></td>";
echo "<input type='hidden' name='id' value='" . $row['ID'] . "'>";
echo "<td><button name='edit' id='edit_btn' class='frm_btns' value='" . $row['ID'] . "'>Edit</button></td>";
echo "</tr>";
}
mysqli_close($con);
?>
It couldn’t read the value of ID, as 0 was returned.
Duplicate Entry error is a very common error that has been experienced by users working with databases. Users have reported that the error has commonly occurred when using the SQL. The error appears when updating the tables. Furthermore, the error has occurred in several scenarios which include using Laravel, PHP, Atlassian, Joomla, and similar web development and databases. Now in this article, the objective is to give you important information regarding the error and to give you some methods by which you can fix the issue by yourself in no time. But before let’s go through its causes.
Causes of Duplicate Entry Error Problem Issue
While researching about the error and its possible solution we come up with some very common users that have been reported by the users. The Duplicate Entry error appears because of multiple reasons depending like if you are working with SQL possible the error comes because of the duplicate key, unique data field, or data type -upper limit. Also if the table indexes are corrupted then also the error seems to appear. However, the error also occurs due to mistakes in the codes or the way the user is updating or modifying the table.
- Duplicate key or entries
- Unique data field
- Data type -upper limit
- Table indexes are corrupted
- Mistakes in the codes
Similar Types of Duplicate Entry Error Problem Issue
- MySQL error 1062 duplicate entry ‘0’ for key ‘primary’
- MySQL for key ‘primary auto_increment
- #1062 – duplicate entry ‘1’ for key ‘primary’ PHPMyAdmin
- ‘0’ for key ‘primary Codeigniter
- Duplicate entry 255 for key ‘primary
- 82 for key primary
- Duplicate entry ‘4294967295’ for key ‘primary
- #1062 40 for key primary
In this section, we will try to cover some methods that you can try to resolve the Duplicate Entry Error. The following are the methods we will go through. Since we do not know the actual cause of the issue we will be giving you solutions according to the scenarios.
1. The Value Already Exist (Duplicate Value)
Now the #1062 – duplicate entry ‘1’ for key ‘primary’ Error may occur when the data or value which you are trying to insert already exists in the Primary key. Furthermore, it is important to know that the Primary key does not accept duplicate entries. To resolve this you can do the below steps.
- STEP 1. Put the Primary Key Colum as to be auto increment
- STEP 2. Use the below syntax
ALTER TABLE ‘table_name’ ADD ‘column_name’ INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
**NOTE: You can ignore the Primary key column while inserting values.
Alternatively,
you can put NULL vale to Primary Key which in turn automatically generates sequence numbers.
2. Unique Data Filed
The error also appears when an existing table has been set to unique. So when you try to add any column the error appears. So the simple fix to this duplicate entry for key ‘primary’ issue is to create a new column but don’t set it to the Unique field. Insert whatever data you wish to insert and the set is as unique if you want to.
3. Data Limit Out Of Range
The error also appears when if you have been using the auto_increment function and the data exceeds the limit of auto_increment function the #1062 – duplicate entry ‘0’ for key ‘primary’ error appears. Suppose you have assigned the primary key column as something. And the limit of the auto_increment is set to a max of 127. Now when you enter a new record whose id is more than 127 the error will emerge. To fix this follow the steps.
- STEP 1. We can resolve the issue by modifying the index field. You may use any of the following signed/unsigned INT/ BIGINT
- STEP 2. Use the below command to increase the maximum range
ALTER TABLE ‘table_name’ MODIFY ‘column_name’ INT UNSIGNED NOT NULL AUTO_INCREMENT;
- STEP 3. Also if you want to retrieve the recently incremented value, the below command
mysql> SELECT LAST_INSERT_ID();
4. Creating a New Database & Importing
If you have tried the above methods and the duplicate entry 0 for key primary error still persists, try the below step to fix the issue.
- STEP 1. Firstly backup your database using the below command
mysqldump database_name > database_name.sql
- STEP 2. Once the backup is done, drop the database
DROP DATABASE database_name;
- STEP 3. Now recreate the database, by using the below command
CREATE DATABASE database_name;
- STEP 4. Now that you have created the database import using the below command
mysql database_name < database_name.sql;
- STEP 5. Now check if the duplicate entry ‘1’ for key ‘primary’ error still occurs
5. When Importing Table from Database in PHPmyadmin
The error has been seen when the user tries to import the exported tables in PHPMyAdmin the duplicate entry for key primary error seems to appear. Follow the steps to do it the right way.
- STEP 1. When you are exporting your SQL database in PHPMyAdmin, use the custom export method
- STEP 2. In the export, method choose Custom- display all possible options
- STEP 3. In the options instead of selecting any of the insert options, choose update
- STEP 4. Using this way will prevent any kind of duplicated inserts to get rid of remove duplicate entry in excel error.
6. Duplicate Username
One of the users has been facing the issue because the database does not allow duplicate usernames. So kindly make sure that the username is unique. To fix this how to remove the duplicate entry in excel issue follow the steps.
- STEP 1. In order to resolve the issue, you have to find find the duplicate usernames, which can be done using the following command
SELECT username FROM #__users GROUP BY username HAVING COUNT(*) > 1
**NOTE: Instead of #_ use the prefix for your tables.
- STEP 2. Fix the 1062 duplicate entry 1 for key primary issue
7. Other Troubleshooting Points
- Error in WordPress Database: So one the cause why this duplicate entry 1 for key primary error occurs is because of adswsc_DbInstall. It is comparing the unequal table names.
- Update the Program: Make sure that if you are using any database application it is updated to the latest version.
- Crosscheck the code: Make sure that the code is accurate and without errors
Conclusion:
In this troubleshooting, we have seen various methods that are the solution to fix Duplicate Entry Error. The error may appear due to multiple reasons and we have tried to cover most of them. Furthermore, we have also talked about the possible causes that lead to this error.
We hope this Duplicate Entry troubleshooting guide fixed your issue. For articles on troubleshooting and tips follow us. Thank You!
Поставить оценку ( рейтинг )
Категория: Joomla 3.x Настройка
Просмотров: 5104
Обновлено: 01.09.2018 05:08
Если сайт не работает и админка тоже и вы видите надпись
Обнаружена ошибка.
1062 Duplicate entry ‘0’ for key ‘PRIMARY’
Тогда применяем:
Решение для Joomla 3.x
1 Вариант решения
Открываем базу вашего сайта, делаем бэкап, затем в PHPMyAdmin и ищем таблицы _updates и _update_sites и чистим их.
Смотрим результат. Всё работает … но, иногда не долго …
через день — два ( зависит от частоты запроса обновлений Joomla ) — снова появляется ошибка 1062.
2 Вариант решения
Этот вариант решения приводится здесь
Аналогично, в PHPMyAdmin и ищем таблицы _updates и _update_sites
Удаляем их.
★★★ Смотрим результат. ➔ Система ругается на отсутствие _updates и _update_sites
создаем их снова примерно так:
CREATE TABLE IF NOT EXISTS `klvxm_updates` (`update_id` int(11) NOT NULL AUTO_INCREMENT,`update_site_id` int(11) DEFAULT 0,`extension_id` int(11) DEFAULT 0,`name` varchar(100) DEFAULT '',`description` text NOT NULL,`element` varchar(100) DEFAULT '',`type` varchar(20) DEFAULT '',`folder` varchar(20) DEFAULT '',`client_id` tinyint(3) DEFAULT 0,`version` varchar(32) DEFAULT '',`data` text NOT NULL,`detailsurl` text NOT NULL,`infourl` text NOT NULL,`extra_query` varchar(1000) DEFAULT '',PRIMARY KEY (`update_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Available Updates';
INSERT INTO `klvxm_update_sites` (`update_site_id`, `name`, `type`, `location`, `enabled`, `last_check_timestamp`) VALUES(1, 'Joomla Core', 'collection', 'http://update.joomla.org/core/list.xml', 1, 0),(2, 'Joomla Extension Directory', 'collection', 'http://update.joomla.org/jed/list.xml', 1, 0),(3, 'Accredited Joomla! Translations', 'collection', 'http://update.joomla.org/language/translationlist_3.xml', 1, 0);
и
CREATE TABLE `klvxm_update_sites` (`update_site_id` int(11) NOT NULL,`name` varchar(100) DEFAULT '',`type` varchar(20) DEFAULT '',`location` text NOT NULL,`enabled` int(11) DEFAULT '0',`last_check_timestamp` bigint(20) DEFAULT '0',`extra_query` varchar(1000) DEFAULT '',PRIMARY KEY (`update_site_id`));
★★★ Смотрим результат. ➔ Всё работает … но, результат не стабилен…
через день — неделю — месяц ( она возникает, когда администратор авторизуется в админке и в это время Joomla пытается обновить приложения ) опять появляется ошибка 1062.
3 Вариант решения
- Заходим в админку, если она работает, если нет, то сначала применяем решение 2
- Чистим Кэш ( ) Административная панель ➯ Система ➯ Очистить весь кэш ✔
- Далее Административная панель ➯ Расширения ➯ Менеджер расширений ➯ Обновить ✔ Найти обновления
Должно помочь.
★★★★★ Проверяем результат.
4 Вариант решения
- Делаем бэкапы
- Заходим в админку, находим плагины фреймворков, которые любят обновляться, например «jsntplframework» plugin
- Удаляем ✔
- Ставим снова ✔
★★★ Смотрим на результаты.
Сама ошибка MySQL — 1062 встречается и в других случаях, которые мы рассмотрим позже
О нашем проекте
Проект Joom-la-la предназначен для начинающих пользователей Системы управления сайтами Joomla; программистов, администраторов. Мы хотим поделиться с вами своими наработками и примерами.
Это один из сотен сайтов, сделанных нами в рамках бренда Petrovich Group. Надеемся быть вам полезными и ждём ваших комментариев
Петрович
Контактная информация
Владивосток, Россия
+ 7 423 2 *** ***
888 (@) jom-la-la.ru
petrovichgroup.ru
****
Новые публикации
Обнаружена ошибка. U…
При попытке сохранить файл configuration появляется сообщение: 0 — Обнаружена ошибка. Unable to load…
После обновления до…
После обновления Joomla до 3.6 в разделе Менеджер расширений — установить появляется Предупреж…
Серия Fatal ошибок в…
В достаточно хороших шаблонах Vina Bonnie, Vina Fashion, IncomeUp, Vina Bagshop есть проблема — они…
[Решено] Ошибка при…
Иногда, при сохранении различного контента ( материала, портфолио), в админке, возникает ошибк…
© Joom-la-la.ru . При любом использовании материалов ссылка на Joom-la-la.ru обязательна.
Все права защищены.
Here at Bobcares, we provide Server Administration and Maintenance services to website owners and web solution providers.
An error we sometimes see in MySQL servers while updating, restoring or replicating databases is: “Error No: 1062” or “Error Code: 1062” or “ERROR 1062 (23000)“
A full error log that we recently saw in a MySQL cluster is:
could not execute Write_rows event on table mydatabasename.atable; Duplicate entry ’174465′ for key ‘PRIMARY’, Error_code: 1062; handler error HA_ERR_FOUND_DUPP_KEY; the event’s master log mysql-bin.000004, end_log_pos 60121977
What is MySQL Error No: 1062?
Simply put, error 1062 is displayed when MySQL finds a DUPLICATE of a row you are trying to insert.
We’ve seen primarily 4 reasons for this error:
- The web application has a bug that adds primary key by large increments, and exhausts the field limit.
- MySQL cluster replication tries to re-insert a field.
- A database dump file contains duplicate rows because of coding error.
- MySQL index table has duplicate rows.
In rare cases, this error is shown when the table becomes too big, but let’s not worry about that for now.
How to fix Error No 1062 when your web appilcation is broken
Every database driven application like WordPress, Drupal or OpenCart distinguishes one user or data set from another using something called a “primary field”.
This primary field should be unique for each user, post, etc.
Web apps use a code like this to insert data:
INSERT INTO table ('id','field1','field2','field3') VALUES ('NULL','data1','data2','data3');
Where “id” is the unique primar key, and is set to auto-increment (that is a number inserted will always be greater than the previous one so as to avoid duplicates).
This will work right if the value inserted is “NULL” and database table is set to “auto-increment”.
Some web apps make the mistake of passing the value as
VALUES ('','data1','data2','data3');
where the first field is omitted. This will insert random numbers into the primary field, rapidly increasing the number to the maximum field limit (usually 2147483647 for numbers).
All subsequent queries will again try to over-write the field with “2147483647”, which MySQL interprets as a Duplicate.
Web app error solution
When we see a possible web application code error, the developers at our Website Support Services create a patch to the app file that fixes the database query.
Now, we have the non-sequential primary key table to be fixed.
For that, we create a new column (aka field), set it as auto-increment, and then make it the primary key.
The code looks approximately like this:
alter table table1 drop primary key;
alter table table1 add field2 int not null auto_increment primary key;
Once the primary key fields are filled with sequential values, the name of the new field can be changed to the old one, so that all web app queries will remain the same.
Warning : These commands can get very complex, very fast. So, if you are not sure how these commads work, it’s best to get expert assistance.
Click here to talk to our MySQL administrators. We are online 24/7 and can help you within a few minutes.
How to fix MySQL replication Error Code : 1062
Due to quirks in network or synching MySQL is sometimes known to try and write a row when it is already present in the slave.
So, when we see this error in a slave, we try either one of the following depending on many factors such as DB write traffic, time of day etc.
- Delete the row – This is the faster and safer way to continue if you know that the row being written is exactly the same as what’s already present.
- Skip the row – If you are not sure there’d be a data loss, you can try skipping the row.
How to delete the row
First delete the row using the primary key.
delete from table1 where field1 is key1;
Then stop and start the slave:
stop slave;
start slave;
select sleep(5);
Once it is done, check the slave status to see if replication is continuing.
show slave status;
If all is well, you’ll see “Seconds_Behind_Master” as a number. If not, your replication is broken and it needs to be fixed.
How to skip the row
For this, you can set the Skip counter to 1.
Here’s how it could look like:
stop slave;
set global SQL_SLAVE_SKIP_COUNTER = 1;
start slave;
select sleep(5);
Then check the slave status to see if replication is continuing.
show slave status;
Again, if all is well, you’ll see “Seconds_Behind_Master” as a number. If not, your replication is broken and it needs to be fixed.
Proceed with caution
Stopping and starting the slave cannot cause any issue unless you havea very busy database. But, the delete statement, skipping and following up with a broken replication requires expert knowledge about MySQL organization and functioning.
If you are not sure how these commands will affect your database, we recommend you talk to a DB administrator.
Click here to consult our MySQL admins. We are online 24/7 and can attend your request within minutes.
How to fix MySQL restore errors
Restore errors usually take the form of:
ERROR 1062 (23000) at line XXXX: Duplicate entry ‘XXXXXX’ for key X”
When restoring database dumps, this error can happen due to 2 reasons:
- The SQL dump file has dulpicate entries.
- The index file is duplicate rows.
To find out what is exactly going wrong, we look at the conflicting rows and see if they have the same or different data.
If it’s the same data, then the issue could be due to duplicate index rows. If it is different data, the SQL dump file needs to be fixed.
How to fix duplicate entries in database dumps
This situation can happen when two or more tables are dumped into a single file without checking for duplicates.
To resolve this, one way we’ve used is to create a new primary key field with auto-increment and then change the queries to insert NULL value into it.
Then go ahead with the dump.
Once the new primary field table is fully populated, the name of the field is changed to the old primary table name to preserve the old queries.
The alter table command will look like this:
alter table table1 change column 'newprimary' 'oldprimary' varchar(255) not null;
If your index file is corrupted
There’s no easy way to fix an index file if there are duplicate entries in it.
You’ll have to delete the index file, and restore that file either from backups or from another server where your database dump is restored to a fresh DB server.
The steps involved are quite complex to list out here. We recommend that you consult a DB expert if you suspect the index file is corrupted.
Click here to talk to our MySQL administrators. We are online 24/7 and can help you within a few minutes.
Summary
MySQL error no 1062 can occur due to buggy web applications, corrupted dump files or replication issues. Today we’ve seen the various ways in which the cause of this error can be detected, and how it can be resolved.
MAKE YOUR SERVER ROCK SOLID!
Never again lose customers to poor page speed! Let us help you.
Sign up once. Enjoy peace of mind forever!
GET 24/7 EXPERT SERVER MANAGEMENT
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
Symptom
You may encounter the following error after copying a MySQL database containing WHMCS data to a new location, or restoring a database backup:
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY' in /path/to/whmcs/vendor/illuminate/database/Connection.php
Cause
This error occurrs when the primary key and auto_increment attributes are absent from one or more tables in the WHMCS database.
Most tables in the WHMCS database will have these attributes on one of the fields.
During the import of the MySQL database table structures at the new location, some data was omitted or an error occurred on the SQL server, resulting in the required structural data failing to copy or restore correctly.
Solution
We recommend dropping the problematic restored database and then working with your server/database administrator for assistance migrating/restoring the database again.
Ensuring that the restoration is performed in such a way as to appropriately restore all the required attributes to the table structure within your WHMCS MySQL database.








