Suppose we have the following 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 called the lastInsertId() method of $stmt , I would not have asked the following question:

lastInsertId() takes the value of the last id from the database connection object. Can such a situation happen that because of the load or something else, $pdo->lastInsertId() will return the id next user after registration, since the first one had not yet managed to take the id value, and the second one had already been registered and recorded the data in the database. And therefore the value of the last id updated in $pdo .

  • As for me, after registration I would authorize by name and password. to eliminate such doubts - Naumov

1 answer 1

Generally speaking it should not, lastInsertId() returns the value for the last inserted value, for the current session / connection. No other session / connection can affect this value. And your lastInsertId() cannot get into parallel sessions. Hundreds of lines can be inserted at the same time, you will get the ID of your last INSERT request.