This is my code:
INSERT INTO titles_production_companies (production_companies_name, production_companies_tmdb_id, title_id)
values
('United Artists', '60','1'),
('Achte Babelsberg Film', '6100','1'),
('Metro-Goldwyn-Mayer (MGM)', '8411','1'),
('Bad Hat Harry Productions', '9168','1')
ON DUPLICATE KEY UPDATE
title_id=LAST_INSERT_ID(title_id),
production_companies_name='United Artists',
production_companies_tmdb_id='60',
title_id='1',
production_companies_name='Achte Babelsberg Film',
production_companies_tmdb_id='6100',
title_id='1',
production_companies_name='Metro-Goldwyn-Mayer (MGM)',
production_companies_tmdb_id='8411',
title_id='1',
production_companies_name='Bad Hat Harry Productions',
production_companies_tmdb_id='9168', title_id='1';
and I've got this message:
Integrity constraint violation: 1062 Duplicate entry '1-Bad Hat Harry
Productions-9168' for key 'uc_production_companies''
The answer in your situation is likely more related to your (My?)SQL server than to PHP.
Let's think of the steps your code is instructed to execute:
Run a INSERT statement
Check if there is any duplicate key in the statement
If duplicate key is detected, fill some of the fields with the given (fixed) values.
Now, if you have a UNIQUE index on any of the fields you fill in by your ON DUPLICATE clause, this will most likely be duplicated on any triggered duplicate INSERT statement.
Looking at your example, it seems you have an index of UNIQUE on your
production_companies_name column which is violated on all ON DUPLICATE triggers, so only the first would work and all the rest will throw out this error.
Possible solutions:
Remove the UNIQUE type index from the production_companies_name column, if any.
Do not attempt to fill in any UNIQUE index with static values.
Do not attempt to fill in any UNIQUE index at all.
Let me know if that helps :-)
Related
SQLSTATE[23000]: Integrity constraint violation: 1452
Cannot add or update a child row: a foreign key constraint fails
(whnkepbk_Hland.interests, CONSTRAINT interests_ibfk_3 FOREIGN KEY (scale_id) REFERENCES scales_reference (scale_id))
I know that the problem is because I have to set value to scale_id to add this data line.
And I do it :
$requete = "INSERT INTO interests (onetsoc_code,element_id,scale_id,data_value) VALUES (:onetsoc_code,:element_id,:scale_id,:data_value)";
...
$InsertMetier->bindParam(':scale_id', $scale);
var_dump($scale);
var_dump($InsertMetier);
$InsertMetier->execute();
Here the content of the var_dump :
</pre>Ol<pre class='xdebug-var-dump' dir='ltr'><small>string</small> <font color='#cc0000'>'Ol'</font>
'INSERT INTO interests (onetsoc_code,element_id,scale_id,data_value) VALUES (:onetsoc_code,:element_id,:scale_id,:data_value)'
My scale variable do have a value according to the var_dump and my query sounds legitimate.
Here a screenshot of my database (interest) :
scales_reference:
Structure of interest :
Structure of scale_reference :
If someone has any idea what I have done wrong.
MySQL error Integrity constraint violation: 1452 from MySQL manual:
For storage engines supporting foreign keys, MySQL rejects any INSERT
or UPDATE operation that attempts to create a foreign key value in a
child table if there is no a matching candidate key value in the
parent table.
That means you are either:
Inserting into your interest table with scale_id value, which doesn't exist in the parent table (scale_reference).
Having error in your query and inserting empty scale_id - from the code snippet it is not clear how you are replacing all placeholders (:xx) with actual values from PHP variables and we don't see the actual query as it is sent to the MySQL server.
You can try to run the desired query directly on MySQL without PHP. If it works, then you have issue in your PHP code.
What's the difference between Ol and OI you can't even see it on stackoverflow , how about "oi" and "ol", yes there is a big difference and I was not putting "OI" but I was putting OL so that was the issue.
I only want to insert if there are no entries where "name" and "email" exist together.
So it's ok if "name" exists with a different e-mail or vica versa.
mysql_query("INSERT INTO
list (name,email)
VALUES ('$name','$email')
ON DUPLICATE KEY
UPDATE name='$name',email='$email'");
I've made both name & email primary keys but the ON DUPLICATE statement is having no effect.
If name and email is your combined unique key, it makes no sense to trigger the update statement (overwriting with the exact same values) if a dataset already exists. In such a case I would really only INSERT and then check if the database responds with a key constraint violation. This is the expected error that is then ignored. Anything else is still an error.
I wouldn't silence this with this NO-OP update.
You need to have a composite unique key to have ON DUPLICATE KEY UPDATE worked:
CREATE UNIQUE INDEX name_email ON list (name, email);
that is why it called ON DUPLICATE **KEY** UPDATE
I need to insert this in a table but only if there isn't a replica of the row already. (both values should be equal). How can I change the code to work this way? Thanks
<?php
mysql_select_db("cyberworlddb", $con);
mysql_query("INSERT INTO Badges (UID, Website)
VALUES ('1', 'www.taringa.net')");
mysql_close($con)
?>
You could create a single index for the UID and Website columns and make that index unique, then use INSERT IGNORE. The result will be that if it is a duplicate, it will just be ignored.
If you need to be able to tell if the SQL inserted a row, then follow it up with a call to mysql_affected_rows() which should return 0 if it didn't do anything and 1 if it inserted the record.
Easiest thing to do is use INSERT IGNORE and have a unique key on the fields. It will insert if no row exists, otherwise do nothing.
What about a unique index on (UID, Website), which would cause the insert to fail?
First up, about the question. It is simple bad to check for "an exact" replica of row in RDBMS. That is just too costly. The right question to ask is what makes my row unique and what is the minimum I can get away with. Putting in unique constraints on big columns is a bad idea.
Answers saying that you should include UID in unique constraint are again just BAD. UID is most likely a generated key and the only input coming from outside is website name. So the only sane thing to do here is to put a unique constraint on website column.
Then the insert code should handle unique constraint errors coming out from the database. You can get the error number from DB handle, like
$errorNo = $mysql->errno ;
Then check for a particular code (1062 in case of MYSQL) that corresponds to unique key violation.
I'm trying to insert items into my postgres table via PHP
But get the following error message ERROR: duplicate key violates unique constraint "search6_idx1"
search6_idx1 is the index table for search6. I tried the following select setval('search6',45) and somehow that only works for sequences.
When you define an index you can optionally make it UNIQUE. Such indexes serve a double purpose:
Speed up queries
Prevent duplicates
In your case, it seems that the problem is one of these:
You are inserting values that already exist
Your index is UNIQUE by mistake
The respective solutions would be:
Don't insert dupes
Make a non-unique index
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.