我使用的MySQLi連接到我的數據庫,我的問題是,我想在數據庫中插入,但我得到這個錯誤:手動插入子表時如何解決外鍵約束失敗錯誤?
Error: Cannot add or update a child row: a foreign key constraint fails (
edi_tracker_revised
.edi_transaction
, CONSTRAINTedi_transaction_ibfk_1
FOREIGN KEY (edi_doc_type_id
) REFERENCESedi_doc_type
(edi_doc_type_id
) ON DELETE CASCADE ON UPDATE CASCADE)
這裏是我的插入代碼。
if ($doc_type == '812') {
$edi_doc_type_id = "SELECT edi_doc_type_id FROM `edi_doc_type` WHERE doc_type = 812 " ;
$sql = "INSERT INTO edi_transaction (`sender_id`,`receiver_id`,`isa_number`,`transaction_date`,`gs_number`,`edi_doc_type_id`,`ref_number`,`file_name`,`file_path`,`creation_date`)
VALUES ('$sender_id','$receiver_id','$isa_number','$transaction_date','$gs_number','$edi_doc_type_id','$ref_number','$file_name','$file_path',NOW()) " ;
$ref_numberArray = explode(',' ,$ref_number); // the ref_number contains the invoice numbers
//Checking query if it is successful
if ($conn->query($sql) === false){
trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error , E_USER_ERROR);
}else {
echo "Successful ! Data is inserted in database ^__^" ;
}
}
當我手動說,我與使用phpMyAdmin的插入,現在如何解決它,如果我第一次填充我的edi_doc_type edi_transaction之前手動?我需要我的edi_transaction表中的edi_doc_type_id。有人能幫助我嗎?
外鍵約束的要點是不要將東西插入受鍵約束的表中。根據你桌子之間的關係,你不應該做你所做的事情。 – Andrew
但我認爲這是一種方式,所以我的數據不會有冗餘,我認爲如果我使用代碼插入,則存在一種傾向,即我將有冗餘數據...所以我該怎麼做?你能幫我嗎? –