The Codesee
The Codesee

Reputation: 3783

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.

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? For example: 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?
}
?>

Upvotes: 1

Views: 98

Answers (1)

Saty
Saty

Reputation: 22532

Get last insert id using $con->lastInsertId; and pass into url

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

Upvotes: 2

Related Questions