简体   繁体   English

插入后获取插入记录的ID

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

I apologize if this question has been asked before, but I was unable to find anything like it. 如果以前曾问过这个问题,我深感抱歉,但找不到类似的东西。

When the user clicks submit, a new record is inserted into my database and the ID is auto-increased by 1 - for example, if the latest record in the database had an ID of 56, the new record would have an ID of 57. 当用户单击“提交”时,新记录将插入到我的数据库中,并且ID自动增加1-例如,如果数据库中的最新记录的ID为56,则新记录的ID为57。

After the record has been inserted into the database, how do I re-direct them to a page which contains a URL variable of the ID of the new record? 将记录插入数据库后,如何将它们重定向到包含新记录ID的URL变量的页面? For example: example.com?id=57 例如: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?
}
?>

Get last insert id using $con->lastInsertId; 使用$con->lastInsertId;获取最后的插入ID $con->lastInsertId; and pass into url 并传递到网址

$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