1

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.

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 Answers1

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