22

I have the following code:

<?
$query =$db->prepare("INSERT INTO a_table (id, a_field) VALUES ('', (:a_field)");
$query->bindParam(":a_field", $a_value);
$query->execute();
$last_id = $db->lastInsertId('a_table');
?>

What I want to ask is this. Imagine when two people load the page at exactly the same time, is it a possible danger that the other persons query is inserted before the last ID is retrieved, mixing up the IDs?

dirk
  • 2,206
  • 4
  • 21
  • 30
  • 14
    No, there will be no conflict. The insert id is dependent upon the connection, and each page load will establish a new connection. – Michael Berkowski Mar 27 '12 at 14:51
  • 5
    Depends on the underlying database. If it's mysql, PDO will simply be calling the mysql last_insert_id() API function, which guarantees that the returned ID is the ID generated by the last insert query performed by your PDO connection. – Marc B Mar 27 '12 at 14:51
  • 1
    possible duplicate of [LAST_INSERT_ID() how it works at multi-users environment](http://stackoverflow.com/questions/5835677/last-insert-id-how-it-works-at-multi-users-environment) – Michael Berkowski Mar 27 '12 at 14:52
  • It is mysql, so I understand I'm safe. Many thanks! Michael, sorry, didn't find the post you are referring to... – dirk Mar 27 '12 at 14:52

3 Answers3

26

No, this situation is impossible. Method $db->lastInsertId() returns last inserted id for this DB conection. In other page will be another connection and another last inserted id.

Andy
  • 576
  • 2
  • 8
  • 18
6

PDO will return you the last ID inserted by the current active database connection.

Pierre-Olivier
  • 3,104
  • 19
  • 37
1

Just faced following situation

Have file post.php which includes another file (like insert.php).

Whole code to insert in mysql is located in insert.php

In insert.php is code $id_of_inserted_row = $db->lastInsertId();

Then in insert.php is echo $id_of_inserted_row; which shows correct value.

But echo $id_of_inserted_row; in post.php shows incorrect value (as i see shows 7 numbers less than actual value). I do not understand why, just need to take into account.

Update

Sorry, above written was because inserted in two tables and mistakenly used the same $id_of_inserted_row = $db->lastInsertId(); for both tables.

So i have the same conclusion as in other answers: lastInsertId() gets id of last inserted row.

Faced situation. I inserted 2 rows in mysql. In such case i see that lastInsertId() is id of the first inserted row (not the last). Do not understand why... Found answer https://stackoverflow.com/a/12574752/2118559

Important If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.

Community
  • 1
  • 1
Andris
  • 1,434
  • 1
  • 19
  • 34