Reputation: 952
I am using a PHP script to send data to my database.
Here is my script:
<?php
session_start();
$correct = true;
$_SESSION['user_id'];
$firstname = $_POST['firstname'] ;
$lastname = $_POST['lastname'] ;
if($correct){
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "INSERT INTO names(user_id, firstname, lastname) VALUES (?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->execute(array($_SESSION['user_id'], $firstname, $lastname));
header('Location: ../names.php');
}
else
{
echo "<p>Error</p>";
}
?>
The script is working fine but after the SQL statement is executed I want to send the user to a page where the user can see the data he entered.
In the current state the script is sending the user to names.php
. I want to send the user to names.php?id=8
.
The id
column is auto increment.
Does someone know how I can send the user to the id
of the executed statement?
Upvotes: 0
Views: 49
Reputation: 145
You can get last inserted id by this,
$id = $db->lastInsertId();
and then you can pass it to header
method. Like below,
header('Location: ../names.php?id='.$id);
Upvotes: 2
Reputation: 357
after your excecute do:
header('Location: ../names.php?id='.$db->lastInsertId);
Upvotes: 3
Reputation: 31
You can try to do another query for Select id from table where user_id=$_SESSION['user_id'] after Insert statement.
Then You can use result on your link names.php?id=[result from Select]
Upvotes: 0