Insert Into Two Tables Using Correct Foreign Key

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dgny06
Forum Commoner
Posts: 25
Joined: Thu Jun 14, 2007 11:35 pm

Insert Into Two Tables Using Correct Foreign Key

Post by dgny06 »

Thanks in advance for any help......

I am doing a real estate site and I have a table to to hold information about a listing (tbListing) and a table that joins to to tbListing via ListingID (tbDescription). The table tbDescription holds only the ListingID primary key and a VARCHAR(1000) that will hold a long description for the listing. Can someone let me know the correct way to to do an insert into the two tables keeping in mind the correct foreign used in the join.

What I was planning on doing was creating a variable and setting its value to be the MAX ListingID from tbDescription + 1. I would then insert that value into tbListing since I know that it would be the next value entered into tbDescription via auto increment. This seems like it would work but I am sure it is not the standard to do what I am trying to do.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Insert Into Two Tables Using Correct Foreign Key

Post by onion2k »

Assuming tbListing has an autoincrement primary key ... insert the record into the listing table, then use mysql_insert_id() to find out what ID it was given and insert the description into the tbDescription table with it.
User avatar
Jaxolotl
Forum Contributor
Posts: 137
Joined: Mon Nov 13, 2006 4:19 am
Location: Argentina and Italy

Re: Insert Into Two Tables Using Correct Foreign Key

Post by Jaxolotl »

I had problems once using mysql_insert_id(), in one server it makes the MySQL server to crash, so i made a function to retrieve it by making a simple sql query end then returning the result

Code: Select all

 
$query ="SELECT LAST_INSERT_ID()";
 
MySQL manual link
http://dev.mysql.com/doc/refman/5.0/en/ ... ue-id.html
Post Reply