0

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?

0

3 Answers 3

3

after your excecute do:

header('Location: ../names.php?id='.$db->lastInsertId); 

PDO::lastInsertId

Sign up to request clarification or add additional context in comments.

1 Comment

I guess you meant header('Location: ../names.php?id=' . $db->lastInsertId);
2

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); 

1 Comment

You forgot a . for string concatenation... :)
0

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.