I have a table in mysql, with primaryKey, Auto Increment and Not Null, when i create a entry with PHP, the primary key os autogenerated, how i can get it with PHP?
I thinked to do $SQL = "SELECT MAX($id) FROM ".$my_table;
but the problem is, if two users make the request almost at the same time, the last record could change.
Another solution is to use START TRANSACTION
, but o dont know how to use exactly in PHP.
Asked
Active
Viewed 1,610 times
1

darkman
- 993
- 3
- 13
- 31
-
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html – Rick Calder Apr 01 '13 at 15:02
-
if you want to keep an order you should work with transaction, how ever remember if you lock a table only 1 user at the time will be able to make a request. – jcho360 Apr 01 '13 at 15:02
1 Answers
3
What you're looking for is mysqli_insert_id:
mysqli_query($link,"INSERT INTO blah VALUES('superblah');");
$newid = mysqli_insert_id($link);
Just request the mysqli_insert_id
after you run the query to return the new ID. Piece of cake.

PlantTheIdea
- 16,061
- 5
- 35
- 40
-
I dont think they ever specified they were using mysqli but its pretty much the same commands just without the "i" at the end. – Lemon Drop Apr 01 '13 at 15:20
-
if they're not using mysqli, they absolutely should be. mysql_* commands are now deprecated. – PlantTheIdea Apr 01 '13 at 16:10