Maybe i have some stupid questions about mysql_insert_id...
I need to get the last inserted Id of a query using mysql_insert_id after mysql_query("INSERT INTO").
mysql_insert_id retrieves the generated Id by the previous query, but my question is...
One php file called test.php with the following code
mysql_query("INSERT INTO table (FirstName, LastName) VALUES ('" . $_POST['FirstName'] . "', '" . $_POST['LastName'] . "'); ")
$lastId = mysql_insert_id();
...continues some code using $lastId
What happens if the test.php file called from different places and different browsers at the SAME TIME ? or what happens if other php file that containts INSERT INTO query called at the same time ?
What actually Id gets back the mysql_insert_id() ? We have to do with a rare probability ?
I do not know if I become understandable...
The PHP manual states that the value of
mysql_insert_id()
returns only the most recently generatedAUTO_INCREMENT
value:The MySQL manual states the it will return the last
AUTO_INCREMENT
based on a per-connection basis:Additionally, you should stop using
mysql_
functions as they are being deprecated.You get back the autoincrement ID from the last query on your connection. It will not cross connections, so there is no harm in two scripts running simultaneously.
Side note: if you have the option, use the mysqli or PDO libraries instead of the deprecated mysql libarary.
Each client will be sitting on a separate connection.
mysql_insert_id()
will get theid
of the lastinsert
query, based on the passed/current connection. So you don't have to worry about multiple scripts causing problems.Also, from the code you provided above, your script is vulnerable to a SQL injection attack. Escape your user-input or even better, use PDO/MySQLi.