Reputation: 137
I am wanting to have the id returned after data is inserted into the database.
There is a strong chance that multiple people will submit their forms at the same time.
I don't want the wrong ID showing up in the results, because this ID will also be recorded in another database log and used to upload files in the next form that shows up to the user.
Is there a chance that if several people submit at the same time that mysqli_insert_id might pick up the wrong id?
Would it be better to do a query on latest date entry for that user and pull the id from there?
Or should I use mysqli_insert_id and then check that id against username in that record to verify that it is the correct one?
Or am I just worrying about something that is not an issue?
Thanks for any input, I am pretty new to this.
Kim :)
Upvotes: 1
Views: 1316
Reputation: 798
you can use mysql_insert_id like this
<?php
$con = mysql_connect("localhost", "peter", "abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("test_db",$con);
$sql = "INSERT INTO person VALUES ('B�rge','Refsnes','Sandnes','17')";
$result = mysql_query($sql,$con);
echo "ID of last inserted record is: " . mysql_insert_id();
mysql_close($con);
?>
Upvotes: -2
Reputation: 360702
last_insert_id()
-type functions are tied to a particular DB connection. You will NOT get the id that some other parallel connection produced, you will not get the id of a connection you did with this script 3 requests ago.
It will ALWAYS be the id of the LAST insert you performed with THIS particular db connection.
It would be utterly useless function if it returned what would essentially be a random number. e.g. Consider a series of parent/child connected tables. You insert the parent record, try to retrieve its ID, and get the ID of some OTHER insert? Now you've "lost" your new record, and would be attaching the children to an invalid parent.
Nope. The function works exactly as you'd expect, and you don't have to worry about getting the wrong ID. The only caveat is that it only retrieves the LAST insert's ID. If you do 2+ inserts in a row, you've lost the IDs of all but the last insert.
Upvotes: 6