Mar1ak
Mar1ak

Reputation: 29

The right way to use foreign keys in PHP

I created two tables. One for students and has stu_id as a PRIMARY KEY, the other one holds information about the student and has stu_id_fk as a FOREIGN KEY.

I set up the relationship between the two using phpmyadmin's interface and it works fine, it even shows which student the foreign key is referencing when hovering the mouse over the value (I inserted some values directly from phpmyadmin not through php code). So I created a student "Billy" when I wanted to insert the student's information I used the following query

$query= " INSERT INTO stu_details (phone,email,location,website,description ) VALUES ('$phone', '$email', '$location', '$website', '$description') ";

and I get this error:

Cannot add or update a child row: a foreign key constraint fails

Now I deduced that when creating a student in the main table, I should also insert a new value in the details table, so when I want to insert the student's information the table will have the stu_id_fk and the rest of the detials will be blank and ready to be inserted. Is that correct?

This is my query for adding a student

$qry= "INSERT INTO students (type,class, username,password,description,reg_date) values ('$type', '$class','$username','$password','$description','$date')"; 

What am I doing wrong? is it that I didn't insert a FOREIGN KEY value in the child table when adding a student in the main table? if yes, how should I edit my query to be able to insert into the two tables in one query, please?

Edit: my question is different than the suggested similar question. I am asking about what to write in the query code in order not to get an error because of the foreign keys.

Thank you.

Upvotes: 0

Views: 759

Answers (1)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

For maintaining FK relationship at code level, you have to follow following rule:

  • Insert the data in master table and get the inserted ID from that insert operation.
  • Insert the data in Child table with that master ID in child table that refers to parent table.

Upvotes: 4

Related Questions