Can anybody tell whether a foreign key in a child table, can automatically get the value it actually has in the parent table? I has two tables student and course table.Student SSC is foreign key in course.I am inserting data correctly into student table.But It gives me an error when I insert data into course table?Any suggestions? Values of variables are got via post method of form.
$query1=mysql_query("INSERT INTO course VALUES('','$subject','$total','$attendce','$ssn')")or die(mysql_error());
This is error I am getting....
Cannot add or update a child row: a foreign key constraint fails (`cast_db`.`course`, CONSTRAINT `course_ibfk_1` FOREIGN KEY (`cnic`) REFERENCES `student` (`cnic`) ON DELETE CASCADE ON UPDATE CASCADE)
That's not how foreign keys work. You have to create a parent record first, get that record's ID (whatever the primary key happens to be) value, and then use that value in your child record insertions.
Remember - a parent table can have MANY records. There is no way for a database to know which of those records is the parent of a new child record. You HAVE to explicitly say that "this new child record has parent X".