繁体   English   中英

如何用外键在表中插入数据?

[英]How to insert data in a table with a foreign key?

我在使用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`)参考`customer_information`(`customer_no`)在删除级联中”)

但是我认为我对此缺乏一些代码。 我只是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有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM