L
L
leni_m2018-06-19 17:09:33
PHP
leni_m, 2018-06-19 17:09:33

How to get the id of the inserted row in the database?

I'm interested in the functions php.net/manual/ru/pdo.lastinsertid.php and
php.net/manual/ru/mysqli.insert-id.php .
For example, there is a script:

$db->query("INSERT ...");
$id = $db->lastInsertId();

and it is launched "simultaneously" from two machines, then there may be such a situation that the server inserts a string from the first machine, then inserts a string from the second machine, and returns the wrong id to the first machine?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2018-06-19
@leni_m

lastInsertId (aka the LAST_INSERT_ID mysql function) is concurrency safe, returns the generated auto increment value for the previous query on that particular connection.
Therefore, if you do insert in one connection, then the subsequent lastInsertId through this connection is guaranteed to return the correct value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question