If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > how to get the auto increment integer primary key value of a new record

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 03-28-04, 23:41
nonno nonno is offline
Registered User
 
Join Date: Mar 2004
Posts: 2
how to get the auto increment integer primary key value of a new record

I have a DB table that has a auto increment integer primary key, if I insert a new record into it by SQL statement "INSERT INTO...", how can I get the integer primary key value of that newly created record?
Reply With Quote
  #2 (permalink)  
Old 03-29-04, 04:30
binkie binkie is offline
Registered User
 
Join Date: Mar 2004
Posts: 7
For this purpose, you can use mysql_insert_id().
It returns the value generated for an auto_increment column by the previous INSERT or UPDATE statement.
Full documentation to be found in the mySQL manual that can be downloaded from www.mysql.com.
Reply With Quote
  #3 (permalink)  
Old 03-29-04, 04:42
navneet_bits navneet_bits is offline
Registered User
 
Join Date: Mar 2004
Location: Pilani
Posts: 3
Thumbs up

hi

The answer to your problem is very simple.
you do one thing whenever you give INSERT statement keep that field blank.

Code:
 INSERT INTO table (id,data1,data2) VALUES ("",$var1,$var2)
when you keep it blank mysql qill automatically increase its value in database.
Reply With Quote
  #4 (permalink)  
Old 03-29-04, 21:53
nonno nonno is offline
Registered User
 
Join Date: Mar 2004
Posts: 2
Thanks binkie. Another question is there may be more than 1 people inserting new records into this table concurrently, so any more things need to do?
Reply With Quote
  #5 (permalink)  
Old 03-31-04, 02:28
binkie binkie is offline
Registered User
 
Join Date: Mar 2004
Posts: 7
mySQL keeps track of more people doing simultaneous inserts. That's why you should NOT use a SELECT MAX(KEY) FROM TABLE because someone else may have inserted a record just after you, and will get the wrong key value.
mySQL links your particular session to the actions that you have executed. By doing so, mysql_insert_id() will return YOUR inserted key, no matter how many people are inserting at that moment.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On