0

I'm using PDO with MySQL. I'm inserting into a table that has the ID field set to autoincrement. I'd like to store that value to reuse in the next line. How can I do this?

muttley91
  • 12,278
  • 33
  • 106
  • 160

1 Answers1

1

From PHP Manual:

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL requires you to specify the name of a sequence object for the name parameter.

return $db->lastInsertId('yourIdColumn');
Emilio Gort
  • 3,475
  • 3
  • 29
  • 44
  • How would this work if two users inserted something at the same time? Wouldn't this mean user1's process would use user2's inserted ID (for example)? – muttley91 Aug 10 '13 at 03:01
  • look this answer http://stackoverflow.com/questions/2675766/pdo-lastinsertid-issues-php#2675791 – Emilio Gort Aug 10 '13 at 03:12
  • 1
    Also see my answer for [Easy mysql question regarding primary keys and an insert](http://stackoverflow.com/questions/165156/easy-mysql-question-regarding-primary-keys-and-an-insert/165254#165254) – Bill Karwin Aug 10 '13 at 03:34
  • @BillKarwin In my tables I always use a column name userId to stored the userid who made the insert/update, I use a query like this, `SELECT max(id) From Table Where userid ='$UserID'` with PDO/mysqli/whatever I don't know is it is the best way. – Emilio Gort Aug 10 '13 at 03:45
  • 2
    @rar: No, because it's not returning the last inserted ID on the table as a whole, but rather the last inserted ID on the PDO object `$db`, which belongs only to the user running that process. – Nick Coons Aug 10 '13 at 04:14
  • @EmilioGort, *any* SELECT statement is limited to transaction scope, and thus creates a race condition with other sessions running the same query to discover the max id. – Bill Karwin Aug 10 '13 at 04:19
  • with stored procedure, i returned the id inserted in that transaction, sorry my English, but what you want to say is that $db->lastInsertId('yourIdColumn') return the last id of the same transaction? – Emilio Gort Aug 10 '13 at 04:26