I am using cleardb
for mysql database in php
. And Situation is something like this:
I am adding record in beneficiary
table. and after adding that I am fetching last_inserted _id
. And using this id
to add payment method in beneficiary_payment_info
. It works fine in most of the cases. But, sometimes I found below message in error log:
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
cdb_85c337008c
.beneficiary_payment_info
, CONSTRAINTbeneficiary_payment_info_ibfk_1
FOREIGN KEY (ben_id
) REFERENCESbeneficiary
(id
))'
When I checked in database, I got this screenshots:
As you can see there is a id 6073
in first table but it's not in second table. I am getting above error just because of this. And there are 2 identical records(6073 and 6081) in first table because user has requested that page second time I guess.
How can I solve this problem? Please guide me. Thanks.
EDIT (Reply from clearDB)
The best course to resolve this issue is to stop involving the auto_increment values.
Rather than trying to guess or set them, you may be able to use a subquery, similar to the following style:
INSERT INTO CHILDREN (ParentID, FirstName, LastName)
VALUES ((SELECT ID FROM PARENTS WHERE FirstName = 'John' AND LastName = 'Doe'),
'Jane', 'Doe');