Auto increment primary key problem (MySQL)

I have 2 tables, each using a different primary key as foreign key. The primary keys for both parameters are set to auto_increment

.

The problem is that when I try to create and log into one of the tables, I have no idea what the primary key of a record is and cannot figure out what to put in the other table as a foreign key. What should I do? Am I dropping auto_increment altogether and preparing a unique ID for each record so that I can use it to address the generated records? I use PHP if appropriate. Thanks.

+2


a source to share


4 answers


Each master database provides a means of finding the identifier of the record just inserted; the idea of ​​auto-incrementing identifiers wouldn't be very useful otherwise.



In MySQL, you can use mysql_insert_id()

. See PHP function of the same name or MySQL function it wraps around.

+4


a source


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



If you are using PDO (which is what you need), you can use PDO :: lastInsertId () instead . This will work for all PDO supported database systems.

+1


a source


You can use this function: mysql_insert_id to insert the last id

0


a source


After the initial insert, mysql_insert_id () will return the auto-incrementing ID value so you can use it in the next insert

0


a source







All Articles