PDO Last Insert ID always the right one?

前端 未结 3 1232
忘掉有多难
忘掉有多难 2020-12-03 17:21

I have the following code:

prepare(\"INSERT INTO a_table (id, a_field) VALUES (\'\', (:a_field)\");
$query->bindParam(\":a_field\",          


        
相关标签:
3条回答
  • 2020-12-03 17:36

    PDO will return you the last ID inserted by the current active database connection.

    0 讨论(0)
  • 2020-12-03 17:40

    Just faced following situation

    Have file post.php which includes another file (like insert.php).

    Whole code to insert in mysql is located in insert.php

    In insert.php is code $id_of_inserted_row = $db->lastInsertId();

    Then in insert.php is echo $id_of_inserted_row; which shows correct value.

    But echo $id_of_inserted_row; in post.php shows incorrect value (as i see shows 7 numbers less than actual value). I do not understand why, just need to take into account.

    Update

    Sorry, above written was because inserted in two tables and mistakenly used the same $id_of_inserted_row = $db->lastInsertId(); for both tables.

    So i have the same conclusion as in other answers: lastInsertId() gets id of last inserted row.

    Faced situation. I inserted 2 rows in mysql. In such case i see that lastInsertId() is id of the first inserted row (not the last). Do not understand why... Found answer https://stackoverflow.com/a/12574752/2118559

    Important If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.

    0 讨论(0)
  • 2020-12-03 17:50

    No, this situation is impossible. Method $db->lastInsertId() returns last inserted id for this DB conection. In other page will be another connection and another last inserted id.

    0 讨论(0)
提交回复
热议问题