简体   繁体   中英

PHP PDO lastInsertId() function confusion

I am confused with the way lastInsertId() function is written. Say for example I have the following queries with lastInsertId() function.

$myinsert = $pdo->prepare("INSERT INTO some_table(something)VALUE(:something");
$myinsert -> bindValue(':something', $something);
$myinsert -> execute();

$insert = $pdo->prepare("INSERT INTO table(something)VALUE(:something");
$insert-> bindValue(':something', $something);
$insert-> execute();
$lastId = $pdo->lastInsertId();

$stmt = $pdo->prepare("INSERT INTO another_table(something)VALUE(:something");
$stmt -> bindValue(':something', $something);
$stmt -> execute();

Now the confusion is that as everyone knows and can see here that in the satement $lastId = $pdo->lastInsertId(); there is no where mentioned whether to fetch the last inserted ID from $myinsert query or $insert query or from $stmt query. So how does it know where to fetch the ID from? Since, lastInsertId() function is placed above the $stmt query, it definitely will not fetch last inserted id from $stmt query as when the $lastid was declared $stmt query was not yet executed. But how does it know it has to fetch from $insert query and not from $myinsert query as in whole statement $lastId = $pdo->lastInsertId(); there is nothing defined like to fetch from so and so particular query? Please help me understand the way it works.

It will just give you the insert ID from the last insert prior to making the call which generates an auto-increment value. It could be that each insert will generate one, but it will only be the last one executed prior to this call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM