tags:

views:

1974

answers:

2

the 'id' field of my table auto increases when I insert a row, I want to insert a row and then get that ID.

I would do it just as I said it but I'm wondering if there's a way I can do it without worrying about the time between inserting the row and getting the id.

I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.

+14  A: 
mysql_query("INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysql_insert_id();

See mysql_insert_id().

Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysql_insert_id() already has this functionality.

cletus
The PDO equivalent is PDO::lastInsertId (http://us3.php.net/manual/en/pdo.lastinsertid.php).
Matthew Flaschen
Cool - didn't know this existed!
Rich Bradshaw
+3  A: 

The mysql function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.

The php function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().

soulmerge