簡體   English   中英

PDO 獲取最后插入的 ID

[英]PDO get the last ID inserted

我有一個查詢,我想插入最后一個 ID。 字段 ID 是主鍵並自動遞增。

我知道我必須使用這個語句:

LAST_INSERT_ID()

該語句適用於如下查詢:

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

但是,如果我想使用此語句獲取 ID:

$ID = LAST_INSERT_ID();

我收到此錯誤:

Fatal error: Call to undefined function LAST_INSERT_ID()

我究竟做錯了什么?

那是因為那是一個 SQL 函數,而不是 PHP。 您可以使用PDO::lastInsertId()

喜歡:

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

如果你想用 SQL 而不是 PDO API 來做,你可以像普通的選擇查詢一樣做:

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

lastInsertId() 僅在 INSERT 查詢之后起作用。

正確的:

$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

您可以通過在連接對象($conn) 上運行 lastInsertId() 方法來獲取最后一個事務的 id。

像這樣 $lid = $conn->lastInsertId();

請查看文檔https://www.php.net/manual/en/language.oop5.basic.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM