0

I'm trying to insert into two tables (parent and child) at the same time from php. This is how I programmed it; I'll insert a unique number together with my original data into the parent table then use the same unique number to fetch the last data I inserted just to get the "id" of the recent data, so I can use it in the child table. It inserts successfully into the first table but did not insert into the second table. I'm getting this error:

Cannot add or update a child row: a foreign key constraint fails (attendance_db.attendance_tb, CONSTRAINT attendance_tb_ibfk_1 FOREIGN KEY (student_id) REFERENCES student_tb (id) ON DELETE CASCADE ON UPDATE CASCADE).

How do I insert into the two tables successfully? Any other method will be accepted. Thanks.

NOTE: I created the relation from the designer menu in phpmyadmin.

DarkRob
  • 3,843
  • 1
  • 10
  • 27
Olawale Oladiran
  • 561
  • 2
  • 11
  • 19
  • Can you show your queries? By the way, if you are using `PDO` (and you should), you could use `PDO::lastInsertId` instead of using a "unique number" – Ermenegildo Aug 27 '19 at 10:04
  • https://stackoverflow.com/questions/21659691/error-1452-cannot-add-or-update-a-child-row-a-foreign-key-constraint-fails – jones Aug 27 '19 at 10:06
  • I am unclear what the unique number is and why you would look up the last inserted id to insert to the child. – P.Salmon Aug 27 '19 at 11:16
  • Hey Ermenegildo, This is my first time hearing or really considering PDO, I'll give it a trial – Olawale Oladiran Aug 27 '19 at 11:27
  • The unique number are the numbers I generated using php microseconds, and the reason why it's in my code is so that I can use it to find the "id" of the row that has that "unique number" (since two rows cannot have the same microseconds cos i've concatenated it with another unique number). I want to get the "id" from the parent table then insert that same "id" in the foreign key of the child table – Olawale Oladiran Aug 27 '19 at 11:30

1 Answers1

1

It seems data is not inserted in your parent table, or id that you are trying to use to insert in child entry does not exist in parent table.

Please make sure foreign key that you are going to insert in child table must be available in parent table (unique/primary id).

Thanks

Kshitij Verma
  • 617
  • 1
  • 4
  • 12
  • Data actually inserted in my parent table and I correctly created the entity relationship with the same info (just the column name is different) – Olawale Oladiran Aug 27 '19 at 11:23
  • and the foreign key in the child table is present in the parent table as well – Olawale Oladiran Aug 27 '19 at 11:24
  • @OlawaleOladiran it may be following issues: 1. You are trying to enter foreign key 0 (but primary key is different) 2. There may be datatype limit issue, if you id -> int(11) in parent table and child table having int(5). In that case. In that case redundant value can be entered which will cause foreign key contraints. – Kshitij Verma Aug 28 '19 at 10:10