Question

I want to insert data into two different tables at the same time using PHP. I have an android application with an interface for entering students information. This information includes student name, student year, course name and grade.

I have 2 tables, The first table has columns for id, student year, student class. The id column is set to auto-increment. The second table has also its own id column also set to auto-increment and in addition has columns for course, grade and id from the first table. This of course is a foreign key in this second table.

My question now is, after inserting student name and student year into the first table, how can I make use of that row id so that it will be a foreign key while inserting the remaining data i.e 2nd table id(already set to auto-increment), course and grade.

For instance, in my android app, if I entered student name as John David, student year as third year, course name as Geo 101 and grade as B, I want to save the name and the year into the first table and after successful execution of that, the student course name and grade should be entered into the second table and the id from the first table for that row that has just been entered should be inserted into the second table also under the column id which is a foreign key referencing first table id.

I just need an idea of how to go through this not necessarily a code.

Thanks.

Was it helpful?

Solution

Something like this:

  INSERT INTO foo (auto,text)
    VALUES(NULL,'text');         # generate ID by inserting NULL
  INSERT INTO foo2 (id,text)
    VALUES(LAST_INSERT_ID(),'text');  # use ID in second table

As per documentation in http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

And for some PHP specific tutorial on your question checkout: http://www.php.net/manual/en/function.mysql-insert-id.php

I am not gonna try to write you PHP code 'cause I have not done it for years :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top