Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

php - PDO get the last ID inserted

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

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 = LAST_INSERT_ID();

I get this error:

Fatal error: Call to undefined function LAST_INSERT_ID()

What am I doing wrong?

question from:https://stackoverflow.com/questions/66067566/how-do-i-get-last-inserted-id-using-sql-or-pdo-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's because that's an SQL function, not PHP. You can use 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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...