获取被插入的记录的ID插入后
问题描述:
我很抱歉如果此问题之前已被询问,但我无法找到任何喜欢它的东西。获取被插入的记录的ID插入后
当用户点击提交时,一条新记录被插入到我的数据库中,并且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和传递到URL
$stmt->execute();
$id=$con->lastInsertId(); ;// get last id
header('Location: example.com?ID=$id');
+0
谢谢,我现在试试 –
+1
last_insert_id不需要事务,因为返回的值始终是当前连接的ID – e4c5
使用最后插入ID http://php.net/manual/en/pdo .lastinsertid.php –