Anonymous
Anonymous

Reputation: 297

How to get id(Auto increment) of last row inserted

Can any one give me SQL query to get id (Which is primary key and auto_incremented) of last row inserted I know there are many answers on this forum about this but no one consider about concurrency problems (or may be i just missed them) that if in mean time any other person execute insert query before getting me last id(from the code below) so this creates problem. Here is the code that i think is not worked well in my situation

$result = mysql_query("
    SHOW TABLE STATUS LIKE 'Media'
");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];

but here also a code may solve my problem

<?php
    $id = mysql_insert_id();
?>

I just want to know if this code gets the insert id of row executed from actual user or the row id of user who inserted after the actual users row execution(or the last row of table).

I know this may be a silly question but i am a PHP developer doesn't know about MYSQL Any help is appreciated.

Upvotes: 2

Views: 200

Answers (1)

icktoofay
icktoofay

Reputation: 129011

mysql_insert_id will return the ID of the last row inserted in the transaction. If you create a new connection to MySQL for each page and don't use multiple threads within a page, mysql_insert_id should do what you want even in the presence of multiple INSERTs happening on different connections, provided you're not doing anything tricky within your PHP page.

Upvotes: 2

Related Questions