开发者

How to insert data in a table with a foreign key?

I have a problem inserting data into a table that has a foreign key using PHP.

I have a table named CUSTOMER_INFORMATION with fields customer_no(PK), first_name, last_name, etc..) and a CATERING_RESERVATION table with fields catering_no(PK), type_of_event, number_of_persons, customer_no(FK), etc...

I want to insert the customer_no in the CATERING_RESERVATION table but I have this error:

Cannot add or update a child row: a foreign key constraint fails (`thesis/catering_reservation`, CONSTRAINT `catering_reservation_ibfk_1` FOREIGN KEY (`customer_no`) REFERENCES `customer_information` (`customer_no`) ON DELETE CASCADE)"

But I think I lack some codes on this. I'm just a newbie in PHP. Really need help.

This is my code

<?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开发者_JAVA技巧_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";

?>


You probably don't have a matching customer with that customer_no. The constraint requires that the rows inserted refer to actual, existing customers. Make sure the customer_no you're trying to insert is valid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜