user934902
user934902

Reputation: 1204

Get unique id of row just inserted into database

I have a form that submits super basic information, just a new name (the name gets assigned a unique id). What I am trying to make happen is when the user submits the name it gets submitted into the database and they get redirected to a new page card.php where they can add more specific information. However the unique id associated with the row that was just submitted needs to follow in the URL (id=$id)

$query = "INSERT INTO name VALUES(NULL, '$name')";

mysqli_query($conn, $query);

$query2 = "SELECT * FROM name ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn, $query2);

while($row = mysqli_fetch_array($result)) {
  $id = $row['id'];
}

header("Location: http://localhost/card.php?id=$id");

Process

addName.php -> user submits new name -> add to database -> redirect to card.php WITH unique id value of name that is just submitted

1.) Is there a way to retain the id of the row just submitted? In the fluke chance 2 or more people submit at the same time the second query of getting the last row inserted into the database will return the wrong row id
2). Having a while loop return 1 piece of info seems like a shitty way to do things, this might be the most basic of shit but i cant seem to return the 1 piece of data without doing this

Upvotes: 0

Views: 915

Answers (2)

Abu Romaïssae
Abu Romaïssae

Reputation: 3901

You could use the mysqli function to retrieve the last inserted id (check mysqli_insert_id as suggested in a comment), but I wouldn't recommend you using the user id in the URL, people can try to get in, using other ids

also you can use the php function to generate a custom is check out: uniqid

Upvotes: 1

Joke_Sense10
Joke_Sense10

Reputation: 5402

Try using mysqli_insert_id which returns the AUTO_INCREMENT ID generated from the previous INSERT operation.

$query = "INSERT INTO name VALUES(NULL, '$name')";

mysqli_query($conn, $query);

$id = mysqli_insert_id();

header("Location: http://localhost/card.php?id=$id");

Reference: https://www.php.net/manual/en/function.mysql-insert-id.php

Upvotes: 1

Related Questions