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

查看:50
本文介绍了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()

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

That statement works with a query like this:

$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 来做,你会像普通的选择查询一样做:

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天全站免登陆