簡體   English   中英

插入后獲取插入記錄的ID

[英]Get the ID of inserted record after being inserted

如果以前曾問過這個問題,我深感抱歉,但找不到類似的東西。

當用戶單擊“提交”時,新記錄將插入到我的數據庫中,並且ID自動增加1-例如,如果數據庫中的最新記錄的ID為56,則新記錄的ID為57。

將記錄插入數據庫后,如何將它們重定向到包含新記錄ID的URL變量的頁面? 例如:example.com?id = 57

<form method="post">
   <input type="text" name="text">
   <input type="submit" name="submit">
</form>

<?php
if(isset($_POST['submit'])) {
   $stmt = $con->prepare("INSERT into database (text) VALUES (:text)");
   $stmt->bindParam(':text', $_POST['text']);
   $stmt->execute();
   header('Location: example.com?ID='); // how do I get the ID of the record which has just been inserted?
}
?>

使用$con->lastInsertId;獲取最后的插入ID $con->lastInsertId; 並傳遞到網址

$stmt->execute();
$id=$con->lastInsertId(); ;// get last id
header('Location: example.com?ID=$id'); 

暫無
暫無

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

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