The Tricky.net

Last inserted id

Probably everybody has already had this problem:


It is great to have an auto_increment field in a database, but once you insert a row in this database and somehow need the created id, things get complicated. I have many times written a query to fetch the row and get the id. However, in mysql / php there is a very useful trick to solve this problem.... it is called mysql_insert_id()


Let's see a small code snippet:


//create the query
$query = "insert into table values('', 'v1', 'v2', ...)"; 
//launch the query
mysql_query($query) or die(mysql_error()); 
//get the last inserted id
$lastId = mysql_insert_id();


That's it! Not very hard, but can save you quite some time!

Comments
Search RSS
Thanks
sheahad (210.56.146.xxx) 15-01-2009 09:45:26

Thanks
Only registered users can write comments!

3.23 Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."