views:

194

answers:

4

I have 2 tables each using other's primary key as a foreign key. The primary keys for both are set to auto_increment.

The problem is, when I try to create and entry into one of the tables, I have no idea what the primary key of the entry is and can't figure out what to put in the other table as a foreign key. What should I do? Do I drop auto_increment altogether and cook up a unique identifier for each entry so I can use it to address the created entries? I'm using PHP, if that's relevant. Thanks.

+4  A: 

Every major database going provides a means of finding the ID of the record you just inserted; the idea of auto-incremented IDs wouldn't be very useful otherwise.

In MySQL, you can use mysql_insert_id(). See the PHP function of the same name or the MySQL function it wraps around.

meagar
But wouldn't it be a problem in case there's a lot of inserts being made in a very short period of time? Would it then send the id of another entry? Thanks.
mathon12
If you're inserting two records and one references the other, you have to make sure they're inserted immediately after each other, or record the `mysql_insert_id()` for the first record and store it if you cannot insert the second record straight away.
meagar
@mathon12 nope.
Col. Shrapnel
Thanks, I hope this works as expected.
mathon12
mysql_insert_id() will return the last insert id per connection basis, so if you've got a lot of traffic on your site and many inserts are performed, each connection gets it's own inserted id's, there will be no problem.
ceteras
Thanks, exactly the question I was asking! :)
mathon12
A: 

You can use this function: mysql_insert_id in order to get the last id inserted

Cristian
Thanks, that should do it.
mathon12
A: 

After the initial insert, the mysql_insert_id() function will return the autoincremented id value so that you can use it in the next insert

Mark Baker
Thanks. I'll look into it :)
mathon12
+1  A: 

mysql_insert_id can give you the value of the last generated value of an autoincrement primary key.

If you're using PDO (which you should), you can use PDO::lastInsertId() instead. This will work for all database systems that are supported by PDO.

Techpriester
Never used PDO before. Interestingly PostgreSQL has a RETURNING keyword which is pretty handy, it seems.
mathon12