Garethp Posted August 17, 2009 Share Posted August 17, 2009 Ok, so I have a table in which I stored ID's, which are unique and auto incrementing (I do this no matter what I use the table for) and I was wondering how I can get the ID of an item I just inserted into the database, without using another query to fetch the last item in the database. I think I saw that code a few weeks ago, but I forgot what it is. Basically, I want something like this mysql_query("INSERT INTO (Name) VALUES ('$Name')"); //Some function to get the ID column of the last query Quote Link to comment Share on other sites More sharing options...
gevans Posted August 17, 2009 Share Posted August 17, 2009 http://us.php.net/manual/en/function.mysql-insert-id.php and the example from that page; <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('mydb'); mysql_query("INSERT INTO mytable (product) values ('kossu')"); printf("Last inserted record has id %d\n", mysql_insert_id()); ?> Quote Link to comment Share on other sites More sharing options...
Garethp Posted August 17, 2009 Author Share Posted August 17, 2009 Perfect, thank you! Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted August 17, 2009 Share Posted August 17, 2009 I was wondering how I can get the ID of an item I just inserted into the database, without using another query to fetch the last item in the database Just FYI, it would be a bad idea to use a second query to select the last inserted ID; there's no guarantee that it is the same as the one you've just inserted because of concurrency issues. For example, if two users (A and B) are loading the page at the same time, it could be that B's insert would happen inbetween A's insert and A's select, resulting in user A receiving the ID that was inserted by user B. The LAST_INSERT_ID() function works on a per-connection basis. It is therefore safe from this kind of thing. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.