RSS Forums RSS
Please support our MySQL advertiser: Programming Forums

generate unique primary key

Join Date: Jun 2005
Location: Kansas City, Missouri, USA
Posts: 345
Reputation: Troy is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 4
Troy's Avatar
Troy Troy is offline Offline
Posting Whiz

Re: generate unique primary key

  #4  
Jun 10th, 2005
The most common scenario is you insert into a table, then you immediately need that new ID to insert into a child table. If this is your case, and you only have one secondary insert (or update) to make, then you can just perform your two queries like so:

MySQL example from mysql.com (in the second insert, the ID is inserted in another table):
INSERT INTO foo (auto,text)VALUES(NULL,'text');
INSERT INTO foo2 (id,text)VALUES(LAST_INSERT_ID(),'text');

If you need that id for other purposes, then you have two choices. You can select it out using a query to SELECT LAST_INSERT_ID(), or you can use PHP's function:
[php]
mysql_query("INSERT INTO mytable (product) values ('SnippetEdit')");
$last_id = mysql_insert_id();
[/php]
Troy Wolf is the author of SnippetEdit. "Website editing as easy as it gets." IX Web Hosting
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 11:01 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC