Export (0) Print
Expand All


SQL Server 2008 R2

Returns the identifier for the row most recently inserted into a table in the database. The table must have an IDENTITY NOT NULL column.

string PDO::lastInsertId ([ $name ] );

$name: An optional string that lets you specify the table.

A string of the identifier for the row most recently added. An empty string if the method call fails.

Support for PDO was added in version 2.0 of the Microsoft Drivers for PHP for SQL Server.

   $database = "test";
   $server = "(local)";
   $conn = new PDO( "sqlsrv:server=$server; Database = $database", "", "");

   $conn->exec("use Test");

   $ret = $conn->exec("INSERT INTO Table1 VALUES( '19' )");
   $ret = $conn->exec("INSERT INTO ScrollTest VALUES( 1, '19' )");

   $lastRow = $conn->lastInsertId('Table1');
   echo $lastRow . "\n";

   // defaults to ScrollTest
   $lastRow = $conn->lastInsertId();
   echo $lastRow . "\n";


Other Resources

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

© 2015 Microsoft