How can I make sure that PDO lastInsertId () does not apply to another simultaneous insertion?

I am making a registration form with an SQL INSERT query using PDO. After this INSERT, I want to extract only userid (automatically incrementing, primary key) and INSERT into another table (table "verification code")

But how can I make sure that this user ID does not belong to the second user who registered 1 / 1000th of a second later than the first user?

Should I find a way to lock the table? Should I use transactions?

+8
php mysql pdo
source share
2 answers

lastInsertId() returns the identifier of the last row inserted in this connection, so concurrent users (with different database connections) will not interfere.

+10
source share

You can avoid this by completing the selection by email or in some unique field. This ensures that you get the correct user ID.

For example:

 select id from user_table where email = 'user@email.com' limit 1; 
+1
source share

All Articles