Re: mysql_db_query & INSERT

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



After you do your first insert, do:

$insertedid = mysql_insert_id();

That will give you the autoincrement ID from the last INSERT you did.  Note, this doesn't retrieve the last autoincrement ID from any insert, just the last one for thta specific mysql connection.  So you don't have to worry about about user's INSERT messing up your operations.

Another note, as a bit of trivia, some database systems allow access to both the last ID inserted for your session or the last ID inserted by any sessions.  Been a couple of years, but I believe in MS SQL Server, using SQL, it was "SELECT @IDENTITY" to get the last inserted ID from any session and "SELECT @@IDENTITY" (two @'s) to get the last one inserted by your session.

Last note, if you do a mysql_close() or break the connection somehow, you've closed that particular session.  Even if you re-open it, you can't do mysql_insert_id() to retrieve your last insert since it's tied to that particular connection.  Once it's closed, you no longer have a handle that points to the previous operations (at least that's how I remember it working..  could always be some caveats I've forgotten).

-TG

= = = Original message = = =

At 8:47 AM +0600 6/20/06, Prathaban Mookiah wrote:
>I have run into a tricky situation and need some help to work my way through
>the problem. I use MySQL.
>
>I accept some data from the user and insert them into two tables.
>
>1. I insert part of the data into the first table. I do not specify the
>primary key field. It is auto generated through auto_increment.  All the
>other fields can have duplicates.
>2. Then I want to insert the other part of the data along with the primary
>key that was automatically generated during the previous insert operation
>into the second table.
>
>My problem is this: How do I retrieve the auto generated primary key field
>in the first table during the first insert operation. I cannot go back to
>the table and query using the data I inserted since as I mentioned earlier
>there can be duplicates. I simply cannot retreive the maximum value since
>some other user could have inserted something during that time.
>
>Any ideas?
>
>Thanks in advance.
>
>Cheers,
>
>Prathap


___________________________________________________________
Sent by ePrompter, the premier email notification software.
Free download at http://www.ePrompter.com.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux