Jump to content

[SOLVED] Getting Newly Stored ID


Garethp

Recommended Posts

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

Link to comment
Share on other sites

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());
?>

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.