如何使用外键在表中插入数据?
将数据插入使用PHP的外键的表中有问题。
我有一个名为CUSTOMER_INFORMATION
的表,其中包含字段customer_no(PK),first_name,last_name等)和CATERING_RESERVATION
表,其中的字段为catering_no(PK),type_of_event,number_of_persons,customer_no(FK)等等。
我想在CATERING_RESERVATION
表中插入customer_no
,但是我有这个错误:
无法添加或更新子行:外键约束失败(`thesis / catering_reservation`,CONSTRAINT`catering_reservation_ibfk_1` FOREIGN KEY(`customer_no`)REFERENCES`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";
?>
您可能没有与该customer_no
匹配的customer_no
。 约束条件要求插入的行引用实际的现有客户。 确保你试图插入的customer_no
是有效的。