Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
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


Community Additions

© 2015 Microsoft