#1062 - Duplicate entry '81057' for key 'PRIMARY' - php

I am not fluent in using phpmyadmin so please be gentle.
I have transferred wordpress sites in the past but they have small databases. Ive now moved a new clients site to my hosting and it is running with this error:
INSERT INTO `wp_options` VALUES ( 81057,
'_wc_session_6f1ee0a5a9d89e47f7941c9e3b3e1fed',
'a:20:{s:4:"cart";s:309:"a:1:{s:32:"7b1ce3d73b70f1a7246e7b76a35fb552";a:9:{s:10:"product_id";i:2103;s:12:"variation_id";s:0:"";s:9:"variation";s:0:"";s:8:"quantity";i:1;s:10:"line_total";d:23;s:8:"line_tax";i:0;s:13:"line_subtotal";d:23;s:17:"line_subtotal_tax";i:0;s:13:"line_tax_data";a:2:{s:5:"total";a:0:{}s:8:"subtotal";a:0:{}}}}";s:15:"applied_coupons";s:6:"a:0:{}";s:23:"coupon_discount_amounts";s:6:"a:0:{}";s:19:"cart_contents_total";d:23;s:20:"cart_contents_weight";i:0;s:19:"cart_contents_count";i:1;s:17:"cart_contents_tax";i:0;s:5:"total";i:0;s:8:"subtotal";d:23;s:15:"subtotal_ex_tax";d:23;s:9:"tax_total";i:0;s:5:"taxes";s:6:"a:0:{}";s:14:"shipping_taxes";s:6:"a:0:{}";s:13:"discount_cart";i:0;s:14:"discount_total";i:0;s:14:"shipping_total";i:0;s:18:"shipping_tax_total";i:0;s:9:"fee_total";i:0;s:4:"fees";s:6:"a:0:{}";s:10:"wc_notices";N;}',
no' ) ;`
#1062 - Duplicate entry '81057' for key 'PRIMARY'
I genuinely do not have a clue what this means and how to change it. I get that there is a duplicate entry and its to do with the primary key - which is set on option_id.
What i don't get is why it doesn't just add the entries into the database and auto increment them - which it is set to do? Also how can i resolve the issue and add the database?
please help !

AUTO_INCREMENT is a default value. If you specify a value for the field it will be used instead.
You can omit the value in the insert statement or use NULL instead.

It looks like the table in your source database has some inconsistency since you are only trying to copy all records to your new database.
Check if there are multiple records with same option_id in your source table and if there are some try to resolve them and then try the import again.
As i understand you are trying to do the manual transfer of the whole database and in that case AUTO_INCREMENT just wont work since you will break the relations between your model entities.

The way I see it, you have two options.
Omit the primary key value and allow mysql to create a new row and auto increment it. Of course this will require you to specify the columns.
INSERT INTO `wp_options`(column2, column3, etc)
VALUES('_wc_session_6f1ee0a5a9d89e47f7941c9e3b3e1fed', ...);
Notice that I left out the primary key
If the data needs to be added to that specific row, do an UPDATE instead.
UPDATE wp_options SET column2='_wc_session_6f1ee0a5a9d89e47f7941c9e3b3e1fed',
column3='something else', ...
WHERE column1=81057

Related

How to create a Manual Insert ID while adding a new row?

I am trying to add new rows in my mysql table using PDO object, but it is giving me automated insert ID.
I need to make primary key values like -
key_1, key_2, key_3... etc.
But for now it's giving me the primary key value as 1,2,3..
Please suggest me some help , thank you.

MySQL - Field 'id' doesn't have a default value

I can't insert any rows into my database, and the error I'm getting is:
This doesn't make any sense as it was working fine before, nothing has changed as far as I know. The ID field is set to primary, not null and auto increment:
I was able to insert a row manually through PHPMyAdmin. Heres the code I'm inserting with:
$query = "INSERT INTO wp_genomics_results (file_id,snp_id,genotype,reputation,zygosity) VALUES (?,?,?,?,?)";
$stmt = $ngdb->prepare($query);
$file_id = $this->fileID;
$snp_id = $row['id'];
$genotype = $this->formatGenotype($extractedGenotype);
$zygosity = $this->assignZygosity($genotype,$minor_allele);
$reputation = $this->assignReputation($zygosity,$genotypes);
$stmt->bind_param("sssss", $file_id,$snp_id,$genotype,$reputation,$zygosity);
$stmt->execute();
I tried deleting the table and creating a new table but it didn't fix it. Is there anything else I can do to try and diagnose and fix this?
make sure for this line:
$stmt->bind_param("sssss",
$file_id,$snp_id,$genotype,$reputation,$zygosity);
First parameter of bind_param() you used is "sssss" that means all off data is string. Please fix it as the right type data of your type on table database.
Please use "i" for integer. For example:
$stmt->bind_param("iisss",
$file_id,$snp_id,$genotype,$reputation,$zygosity);
I make the code above as an example because I can not see all of your table descibe.
I tried inserting with the WordPress database connection:
$wpdb->query("INSERT INTO wp_genomics_results (file_id,snp_id,genotype,reputation,zygosity) VALUES ('$file_id','$snp_id','$genotype','$reputation','$zygosity')");
and it works, but if I try using an identical query with my own database connection:
$db = new mysqli('localhost', NG_DB_USER, NG_DB_PASS, NG_DB_NAME);
$db->query("INSERT INTO wp_genomics_results (file_id,snp_id,genotype,reputation,zygosity) VALUES ('111','$snp_id','$genotype','$reputation','$zygosity')");
I get the same error:
Error No: 1364 - MySQL error Field 'id' doesn't have a default value
I don't understand why it works with wordpress but not my own database connection. I went into my mysql.ini file and changed this:
sql-mode="STRICT_ALL_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ZERO_DATE,
NO_ZERO_IN_DATE,NO_AUTO_CREATE_USER"
to this:
sql-mode=""
and now I can insert a row, the error stopped happening. I still don't understand why this error was occuring to begin with. And now theres a new error happening:
Duplicate entry '0' for key 'PRIMARY'
I don't understand it because the id column is set to auto increment. Theres also no rows in there with ID = 0. I even emptied the table to make absolute sure there is no row in there with ID = 0. I'm very confused about whats happening. Heres the output of the table structure:
> mysql> SHOW CREATE TABLE wp_genomics_results;
| wp_genomics_results | CREATE TABLE `wp_genomics_results` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`file_id` int(11) NOT NULL,
`snp_id` int(11) NOT NULL,
`genotype` varchar(3) NOT NULL,
`reputation` varchar(3) NOT NULL,
`zygosity` int(3) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)
I notice it says 1 row in set, but the table is actually empty. And once again, I'm able to insert a new row through PHPMyAdmin:
Oh God I feel like an idiot. All this time, the problem was that I had the wrong database selected. So it was querying a table from a different database, and this tables ID field didn't have auto increment set. Ah well, it was a good learning experience, getting to know MySQL better.
EDIT
The table definition looks really strange. It looks like there's a second index on the id column. The id column is already defined as the PRIMARY KEY.
It's this line in the table definition that is bothers me...
KEY `id` (`id`)
It's bizarre that MySQL would even let you add a second index on the same column, and not return an error like "such an index already exist" or "the set of columns is already indexed" or such.
I recommend you run a statement to drop the index named id. Execute either
DROP INDEX `id` ON `wp_genomics_results`;
-or-
ALTER TABLE `wp_genomics_results` DROP KEY `id`;
It's possible that this index was contributing to the issue.
ORIGINAL ANSWER
I suggest you figure out exactly which statement is throwing an error.
I suspect it's not the execution of INSERT INTO wp_genomics_results statement.
If it were me, I'd take a look at the assignZygosity and assignReputation functions. I suspect the culprit is in down in there.
I suspect there's something going on in those functions. My guess (just a guess) is that one of those functions is performing a lookup to get a value for a foreign key. And, if a foreign key value isn't found, something is being executed to INSERT a row into the referenced table. There must be some reason that function is being called, some reason we're not just using the value supplied as a parameter...
The formatGenotype function is also a suspect, by proximity. (I'm less a-feared of that function name... but again, I have no idea what that function is doing.)
If that's not the issue, if it's really the execution of the INSERT statement shown in the code, then I'd look for a "BEFORE INSERT" trigger on the wp_genomics_results table... maybe the trigger is performing an insert to some other table.
As a quick test, I'd comment out the calls to those functions, and just assign a literal values to $zygosity and $reputation.
I want to know the exact line number in the exact file where the error is being thrown.
I also want the complete error message from MySQL.
Following every execution of a database interaction, I want to check the return, and if there's an error, I want (for debugging purposes) a unique message that indicates where we are in the code when the error is thrown, along with the complete error message returned from MySQL (mysqli_error).
I'm not going to just assume, without evidence, that it's the execution of this particular statement that's causing the error.
And if it really is this statement, then we'd need to take a look at the actual MySQL definition of the table... the output from a SHOW CREATE TABLE wp_genomics_results statement.
And we want to make sure that we are looking at the same MySQL instance and database that the code is connecting to, and not some other MySQL instance or database.

ID cannot be null (Auto Increment)

I'm using an INSERT ON DUPLICATE KEY statement for my website. It's for creating news items, so I figured I could use the same MySQL command for both creating and updating news items.
However, when I use the following:
INSERT INTO table (id,title,content) VALUES(NULL,"Test","Test");
Instead of creating a new auto increment value it throws an error. However, the command works on my main development server. But not on my laptop. Both versions of MySQL are the same, the only difference being MySQL was installed manually on my server, and with WAMP on my laptop.
Are there any MySQL Variables that could be causing this?
I would suggest using INSERT INTO table (title,content) VALUES("Test","Test");
This will create a new row in the table with a new incremented ID.
Managed to solve it as best as I can.
I checked my code and found that when I inserted the empty POST'd ID was wrapping it in quotations. I've now changed it so that it puts NULL without quotations. So my query should now look like:
INSERT INTO table (id,title,content) VALUES(NULL,"test","Test")
ON DUPLICATE KEY UPDATE title=VALUES(title), content=VALUES(content);
That now works.
I think you should make query like this,
INSERT INTO table (title,content) VALUES("Test","Test");
If it still doesn't work then check if id column is set as auto-increment or not.

Is it possible to insert a row but only if a value does not already exist?

Is it possible to insert a row, but only if one of the values already in the table does not exist?
I'm creating a Tell A Friend with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't want any more than 1 person getting the referral points once the new customer signs up and purchases something. Therefore I want only one email ever once in the table.
I'm using PHP 4 and MySql 4.1.
This works if you have a unique index or primary key on the column (EmailAddr in this example):
INSERT IGNORE INTO Table (EmailAddr) VALUES ('test#test.com')
Using this if a record with that email already exists (duplicate key violation) instead of an error, the statement just fails and nothing is inserted.
See the MySql docs for more information.
If the column is a primary key or a unique index:
INSERT INTO table (email) VALUES (email_address) ON DUPLICATE KEY UPDATE
email=email_address
Knowing my luck there's a better way of doing it though. AFAIK there's no equivalent of "ON DUPLICATE KEY DO NOTHING" in MySQL. I'm not sure about the email=email_Address bit, you could play about and see if it works without you having to specify an action. As someone states above though, if it has unique constraints on it nothing will happen anyway. And if you want all email addresses in a table to be unique there's no reason to specify it as unique in your column definition.
Most likely something like:
IF NOT EXISTS(SELECT * FROM myTable WHERE Email=#Email) THEN INSERT INTO blah blah
That can be rolled into one database query.
A slight modification/addition to naeblis's answer:
INSERT INTO table (email) VALUES (email_address)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)
This way you don't have to throw email=email_address in there and you get the correct value for LAST_INSERT_ID() if the statement updates.
Source: MySQL Docs: 12.2.5.3
MySQL offers REPLACE INTO http://dev.mysql.com/doc/refman/5.0/en/replace.html:
REPLACE works exactly like INSERT,
except that if an old row in the table
has the same value as a new row for a
PRIMARY KEY or a UNIQUE index, the
old row is deleted before the new row
is inserted.
I'm not sure if I got it, but what about a
try {
mysql_query($sql);
}
catch(Exception $e) {
}
combined with an unique field index in MySQL?
if it throws an exception then you know that you got a duplicated field.
Sorry if that don't answer your question..
If the email field was the primary key then the constraints on the table would stop a duplicate from being entered.

Auto increment stopped in MySQL?

I'm working on a script that sadly I inherited - with no commenting or anything. Argh!
For testing purposes I duplicated one of the tables in the database which had an auto-incrementing ID. When the data is saved to the database, though, the ID number just reads "0" -- which is the default for that column. I'm not sure why it's not auto increasing anymore... any thoughts? Thank you!
Are you sure you set the field in the duplicate table to auto-increment? Try running:
ALTER TABLE `duplicate_table` CHANGE `ai_key` `ai_key` INT( key_length ) NOT NULL AUTO_INCREMENT
And see if it is set or not.
Did you create the new table from scratch or as a real copy? If the column is supposed to auto increment it should be a primary (or at least a unique) key, with no default value.
Just to double check use the sql statement to show the show create table syntax for both tables and compare.
show create table <table>
It sounds like your column isn't actually auto_increment any more. This has happened to me a couple of times because there was a bug (?) in phpMyAdmin which I used to create backups: it wouldn't add the auto_increment keyword into the CREATE TABLE statements. That was a massive pain in the butt...

Categories