Skip to main content
Participant
Feb 4, 2011 8:54 PM UTC
Question

How do you insert new records into multiple tables using the same unique primary key?

I’ve created a PHP site and MySQL server using a free app called XAMPP.  I have successfully created a form in Dreamweaver that will write data to a (name) table in the SQL database.  Here’s my question: How do you write to two (or more) tables in the same database and pass the same primary key to both tables?  In the SQL database, I defined the first field as ID and set it as the primary key with auto update.  So, when you insert a new record, it creates a unique primary key for that record.  In my form, I’m capturing info that needs to be stored to two tables at the same time; a Name table and Address table. Since the Name and Address tables use the ID field as the primary key, I believe I will need to pass the ID value from the Name table to the insert of the Address table to insure they both have the same primary key, right?

This topic is closed to new replies. Start a new post to keep the conversation going.

1 reply

Participating Frequently
Feb 4, 2011 11:07 PM UTC

No. You probably need the primary key from one table to be a foreign key in the other tables. In any case, I believe you can use two methods to obtain the auto generated key. First with SQL:

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

And the other using a PHP function:

http://us3.php.net/mysql_insert_id

Translate