2016-07-22 99 views
1

我很抱歉如果此問題之前已被詢問,但我無法找到任何喜歡它的東西。獲取被插入的記錄的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? 
} 
?> 
+0

使用最後插入ID http://php.net/manual/en/pdo .lastinsertid.php –

回答

2

使用$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