是否必须在调用 lastInsertId() 之前插入一条新记录以获取 PDO 中最后插入的 ID?

Is it mandatory to insert a new record just before calling lastInsertId() to get the last inserted ID in PDO?

我正在努力学习 PDO。

首先,我使用下面的代码成功地在 table 中插入了一条记录。

<?php
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "myDBPDO";

  try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
  }
  catch(PDOException $e) {
    echo $sql . "<br>" . $e->getMessage();
  }

  $conn = null;
?>

然后,我尝试获取最后插入记录的ID。我为此编写了以下代码:

<?php
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "myDBPDO";

  try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $last_id = $conn->lastInsertId();
    echo "Last inserted ID is: " . $last_id;
  }
  catch(PDOException $e) {
    echo $sql . "<br>" . $e->getMessage();
  }

  $conn = null;
?>

上面(第二个代码片段)的输出如下:

Last inserted ID is: 0

实际上,我希望得到以下输出:

Last inserted ID is: 1

1是我在第一个程序中插入的记录的ID字段中的值。

为什么它没有返回上面指定的预期输出?

是否必须在调用 lastInsertId() 以获取 PDO 中最后插入的 ID 之前插入一条新记录?

如果是,那么在使用我编写的第二个代码片段调用 lastInsertId() 之前,我应该如何在不插入新记录的情况下获取最后插入的 ID?如果不是,是什么原因?

基础数据库调用 LAST_INSERT_ID() 按连接操作。如果断开连接,值将丢失

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client

所以回答你的问题...

Is it mandatory to insert a new record just before calling lastInsertId() to get the last inserted ID in PDO?

是的,没错。


how should I get the last inserted id without inserting a new record

您几乎只能获取最大 ID 值

$maxId = $conn->query('SELECT MAX(id) FROM MyGuests')->fetchColumn();

或者,将第一个脚本中的 lastInsertId() 值保存在第二个脚本可以检索到的某个地方。