Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO Last Insert ID always the right one?

Tags:

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?

like image 436
dirk Avatar asked Mar 27 '12 14:03

dirk


People also ask

How can I get last insert ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

What is last insert ID?

The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

How do I get the last inserted ID in SQL?

SELECT @@IDENTITY @@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope.

How do you find the last inserted value?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.


1 Answers

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.

like image 190
Andy Avatar answered Oct 29 '22 11:10

Andy