PDO::lastInsertId

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

Syntax

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

Parameters

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

Return Value

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

Remarks

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

Example

<?php
   $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";
?>

See Also

Reference

PDO Class

Other Resources

PDO