PDO获取插入的最后一个ID [英] PDO get the last ID inserted

查看:2847
本文介绍了PDO获取插入的最后一个ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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()

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

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

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

$ID = LAST_INSERT_ID();

我收到此错误:

Fatal error: Call to undefined function LAST_INSERT_ID()

做错了?

推荐答案

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

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

喜欢:

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

如果你想用SQL代替PDO API, select query:

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

这篇关于PDO获取插入的最后一个ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆