Re: mysql_db_query & INSERT
| From: | tg-php at gryffyndevelopment dot com | Date: | Tue, 20 Jun 2006 15:03:12 +0000 |
| Subject: | Re: mysql_db_query & INSERT | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-238409@lists.php.net to get a copy of this message | ||
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.