Page 1 of 1
PHP: Return ID of record just inserted?
Posted: Wed Jul 16, 2014 9:33 pm
by OldRod
I have a PHP script that inserts a record into a MySQL table. The table has an auto-increment ID field. Is it possible to capture the ID of the record that just got inserted and then return that back to the calling script?
Re: PHP: Return ID of record just inserted?
Posted: Wed Jul 16, 2014 9:37 pm
by Xaos
You could add time-stamps and look for the most recent one.
Re: PHP: Return ID of record just inserted?
Posted: Wed Jul 16, 2014 9:40 pm
by Sharlenwar
You could use:
Code: Select all
echo "Last Insert Id: " . $db->lastInsertId() . "<br>";
Reference:
http://ca3.php.net/manual/en/pdo.lastinsertid.php
Not sure if that will help.
Re: PHP: Return ID of record just inserted?
Posted: Wed Jul 16, 2014 10:12 pm
by OldRod
That looks promising. I will try that, thanks

Re: PHP: Return ID of record just inserted?
Posted: Wed Jul 16, 2014 10:34 pm
by Jackolantern
OldRod wrote:
That looks promising. I will try that, thanks

Yeah, definitely try that. Sadly, this very common need is not fulfilled by the SQL standard, and so every vendor implements their own way to get it.
Re: PHP: Return ID of record just inserted?
Posted: Thu Jul 17, 2014 2:49 am
by Callan S.
Making a comment to put this on my comment record, for latter potential use. I've run into this, where I tried to give it a value then looked it up immediately after - fairly clunky method to deal with it.
Re: PHP: Return ID of record just inserted?
Posted: Wed Jul 23, 2014 11:17 am
by MikuzA
My having that function, one thought crosses my mind.. I remember talking this with a buddy of mine and testing it or something..
But, does the function retrieve 'the last id of the inserted row in db' or 'the last id of the inserted row of the current connection/session in db'.
I remember doing a massive loop, opening it separate computers/browsers just to try breaking this to confirm which one it is..
Like inserting simulationiously huge amount of data and printing out the last id everytime..
Then just comparing the results towards the database..
What my results was that it was actually always 'that' sessions last id. Not sure thought if my test was sufficient enough.. and the answer to this might be found on the notes of this function..
Just adding it here for a precaution and discussion for further information!

Re: PHP: Return ID of record just inserted?
Posted: Wed Jul 23, 2014 2:25 pm
by Sharlenwar
I used this to see how many items were insertted into my map database. I have a grid of 9x9 tiles and so there are 81 tiles. I used this to give me that number to confirm that it loaded in right.