【问题标题】:Get the ID of inserted record after being inserted插入后获取插入记录的ID
【发布时间】:2016-11-26 02:03:32
【问题描述】:

如果以前有人问过这个问题,我深表歉意,但我找不到类似的问题。

当用户点击提交时,一条新记录被插入到我的数据库中,并且 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?
}
?>

【问题讨论】:

标签: php html pdo sql-insert


【解决方案1】:

使用$con-&gt;lastInsertId;获取最后插入id并传入url

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

【讨论】:

  • 谢谢,我现在就试试这个
  • last_insert_id 不需要事务,因为返回的值始终是当前连接的 id
猜你喜欢
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多