Re: Grabbing auto_increment during insert?

From: Date: Mon, 07 Oct 2002 21:46:49 +0000
Subject: Re: Grabbing auto_increment during insert?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-119143@lists.php.net to get a copy of this message
> Apologies for what's probably an extremely newbie question.. > > Is there any way to have a database return its auto_increment field > during insert? I have two different tables, when one inserts, I'd like > to be able to assign the value of the new auto_increment field to > another field in another table. > > I guess I COULD go and make the second table auto_increment along with > it, but that would require a complete rewrite, and I'd like to avoid that... > > Anyone have ideas, suggestions, or preferably.. an answer to my question? :) Two ways: 1. Do your first INSERT and then pull out the created ID with the PHP function mysql_insert_id(). Use that value in your next query. INSERT INTO table VALUES (null,'John'); $id = mysql_insert_id(); INSERT INTO table2 VALUES ($id,'Address','Other Stuff'); 2. Do your first insert, and then use the MySQL function LAST_INSERT_ID() in your second query. INSERT INTO table VALUES (null,'John'); INSERT INTO table2 VALUES (LAST_INSERT_ID(),'Address','Other Stuff'); ---John Holmes...

« previous php.general (#119143) next »