Question:
Let's say we have this code:
$stmt = $pdo -> prepare("INSERT INTO users (email,password) VALUES (:email,:password)");
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->execute();
$_SESSION['id'] = $pdo->lastInsertId();
If I were to call the lastInsertId()
method on $stmt
, I wouldn't ask myself the following question:
lastInsertId()
takes the value of the last id
of the database connection object. Can it happen that due to load or something else $pdo->lastInsertId()
will return the id
of the next user after registration, because the first has not yet had time to take the id
value, and the second has already been registered and written the data to the database. And consequently $pdo
updated with the value of the last id
.
Answer:
Generally speaking, it shouldn't, lastInsertId()
returns exactly the last value inserted, for the current session/connection. Other sessions/connections cannot influence this value in any way. And your lastInsertId()
can't get into parallel sessions. Hundreds of rows can be inserted at the same time, you will get the ID of your last INSERT query.