php PDO 获取最后插入的 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10680943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:47:43  来源:igfitidea点击:

PDO get the last ID inserted

phpmysqldatabasepdo

提问by William Kinaan

I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.

我有一个查询,我想插入最后一个 ID。字段 ID 是主键并自动递增。

I know that I have to use this statement:

我知道我必须使用这个语句:

LAST_INSERT_ID()

That statement works with a query like this:

该语句适用于这样的查询:

$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";

But if I want to get the ID using this statement:

但是,如果我想使用此语句获取 ID:

$ID = LAST_INSERT_ID();

I get this error:

我收到此错误:

Fatal error: Call to undefined function LAST_INSERT_ID()

What am I doing wrong?

我究竟做错了什么?

回答by Corbin

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

那是因为那是一个 SQL 函数,而不是 PHP。您可以使用PDO::lastInsertId().

Like:

喜欢:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

如果你想用 SQL 而不是 PDO API 来做,你可以像普通的选择查询一样做:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

回答by Ayhan Kesicio?lu

lastInsertId() only work after the INSERT query.

lastInsertId() 仅在 INSERT 查询之后工作。

Correct:

正确的:

$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass) 
                              VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();

Incorrect:

不正确:

$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0

回答by Kanton Samad

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

您可以通过在连接对象 ($conn) 上运行 lastInsertId() 方法来获取最后一个事务的 id。

Like this $lid = $conn->lastInsertId();

像这样 $lid = $conn->lastInsertId();

Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

请查看文档 https://www.php.net/manual/en/language.oop5.basic.php