0

I am trying to insert data in sql server 2005 using PDO object in PHP.

Also I want to retrieve last inserted id which is auto generated.

any one help me.

ashish bhatt
  • 3,091
  • 5
  • 25
  • 23

1 Answers1

1

In the session that the insert occured issue a

select scope_identity()

will return the last generated identity column inserted.

benjamin moskovits
  • 5,261
  • 1
  • 12
  • 22
  • This isn't how it should be done. It can be done with one call to db. http://php.net/manual/en/pdo.lastinsertid.php – chris85 Mar 18 '15 at 12:35
  • 1
    I don't know PHP so this being a SQL Server group I gave the SQL Server answer. It may not be appropriate in a PHP client program. – benjamin moskovits Mar 18 '15 at 12:56
  • @chris85 I also don't know PHP but that seems to have a potential issue. What if there is a insert trigger on the table? Does it return the last identity value from the base table or the value from the trigger? – Sean Lange Mar 18 '15 at 13:39
  • I just tried inserting on a table with a trigger. In the main session it returned the identity column value from the table not from the table that was inserted through the trigger. – benjamin moskovits Mar 18 '15 at 14:23
  • Here's another thread on it, http://stackoverflow.com/questions/5931165/mysql-and-pdo-could-pdolastinsertid-theoretically-fail. With the `scope_identity` I think you could get incorrect values. I'd need to see a full code sample to advise more though. – chris85 Mar 18 '15 at 18:59
  • That conversation seems to be about Mysql. In SQL Server you will always get the last identity value automatically created in a given session. – benjamin moskovits Mar 18 '15 at 20:19