pdo获取插入的最后一个id

lfapxunr  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(596)

我有一个查询,我想插入最后一个id。字段id是主键并自动递增。
我知道我必须用这句话:

LAST_INSERT_ID()

该语句适用于以下查询:

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

但是如果我想用这个语句得到身份证:

$ID = LAST_INSERT_ID();

我得到这个错误:

Fatal error: Call to undefined function LAST_INSERT_ID()

我做错什么了?

hfyxw5xn

hfyxw5xn1#

lastinsertid()只能在插入查询之后工作。
对的:

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

不正确:

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

busg9geu2#

这是因为这是一个sql函数,而不是php。你可以用 PDO::lastInsertId() .
比如:

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

如果要使用sql而不是pdo api执行此操作,您可以像执行普通的select查询一样执行此操作:

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

xcitsw883#

通过对连接对象($conn)运行lastinsertid()方法,可以获得上一个事务的id。
像这样$lid=$conn->lastinsertid();
请检查一下文件https://www.php.net/manual/en/language.oop5.basic.php

相关问题