我在使用PHP将数据插入到具有外键的表中时遇到问题。
我有一个名为CUSTOMER_INFORMATION
的表,其字段为customer_no(PK),first_name,last_name等。)和一个CATERING_RESERVATION
表,其字段为catering_no(PK),type_of_event,number_of_persons,customer_no(FK) )等等......
我想在customer_no
表中插入CATERING_RESERVATION
但我有这个错误:
无法添加或更新子行:外键约束失败 (`thesis / catering_reservation`,CONSTRAINT `catering_reservation_ibfk_1` FOREIGN KEY(`customer_no`) 参考`customer_information`(`customer_no`)ON DELETE CASCADE)“
但我认为我缺少一些代码。我只是PHP的新手。真的需要帮助。
这是我的代码
<?php
$con = mysql_connect("localhost","root","");
if(!$con){
die('could not connect:'.mysql_error());
}
mysql_select_db("thesis",$con);
//from customer information fill up form
$first_name=$_POST['first_name'];
$middle_name=$_POST['middle_name'];
$last_name = $_POST['last_name'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip_code = $_POST['zip_code'];
$email_address = $_POST['email_address'];
$phone_number = $_POST['phone_number'];
$mobile_number = $_POST['mobile_number'];
$sql="INSERT INTO customer_information (first_name,middle_name,last_name,address,city,zip_code,email_address,phone_number,mobile_number) VALUES('$first_name','$middle_name','$last_name','$address','$city','$zip_code','$email_address','$phone_number','$mobile_number')";
if(!mysql_query($sql,$con)){
die('Error' .mysql_error());
}
echo " 1 record added";
//from catering infomation fill up form
$type_of_event = $_POST['type_of_event'];
$number_of_person = $_POST['number_of_person'];
$month = $_POST['month'];
$mobile_number = $_POST['day'];
$year = $_POST['year'];
$start_time = $_POST['start_time'];
$end_time = $_POST['end_time'];
$esetup_time = $_POST['esetup_time'];
$eventplace_name = $_POST['eventplace_name'];
$eventplace_address = $_POST['eventplace_address'];
$comment = $_POST['comment'];
$sql2="INSERT INTO catering_reservation (type_of_event,number_of_person,month,day,year,start_time,end_time,esetup_time,eventplace_name,eventplace_address,comment) VALUES('$type_of_event','$number_of_person','$month','$day','$year','$start_time','$end_time','$esetup_time','$eventplace_name','$eventplace_address','$comment')";
if(!mysql_query($sql2,$con)){
die('Error' .mysql_error());
}
echo " 1 record added";
?>
答案 0 :(得分:1)
您可能没有与customer_no
匹配的客户。约束要求插入的行引用实际的现有客户。确保您尝试插入的customer_no
有效。