Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the ID of the last INSERTed row using PDO with SQL Server?

Under other circumstances I might be tempted to use

$result = mssql_query("INSERT INTO table (fields) VALUES (data); 
                       SELECT CAST(scope_identity() AS int)");

but as I will be inserting user-submitted data, I want to continue to use PDO, which returns an empty array.

Unfortunately, I'm running PHP on a Linux server and using dblib to interface with Microsoft SQL Server, which doesn't support PDO::lastInsertID().

Please help!

Update to include code example

Here's the code I'm using: col1 is a field of type int identity and col2 is a datetime with a default of getdate().

//  Connect to db with PDO
$pdo = new PDO( 'dblib:host=' . $host . ';dbname=' . $database . ';', $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
//  Connect to db with MSSQL
$sql = mssql_connect( $host, $username, $password );
mssql_select_db( $database, $sql );
//  Create SQL statement
$query = "INSERT INTO [table] ( col3, col4, col5 )
          VALUES ( 'str1', 'str2', 'str3' );
          SELECT SCOPE_IDENTITY() AS theID;";
//  Run with MSSQL
echo "Using MSSQL...\n";
$result = mssql_query( $query );
$the_id = mssql_result( $result, 0, 'theID' );
echo "Query OK. Returned ID is " . $the_id . "\n";
// Run with PDO
echo "\nUsing PDO...\n";
$stmt = $pdo->query( $query );
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
print_r( $result );

And this is what was displayed:

Using MSSQL...
Query OK. Returned ID is 149

Using PDO...
Array
(
)

I would love to find out that I'd done something stupid, rather than come up against a horrible dead end :)

like image 562
Kalessin Avatar asked May 26 '11 14:05

Kalessin


People also ask

How do I get the last inserted row ID in SQL?

SELECT IDENT_CURRENT('tablename') To avoid the potential problems associated with adding a trigger later on, always use SCOPE_IDENTITY() to return the identity of the recently added row in your T SQL Statement or Stored Procedure.

Which method of the PDO class gets the ID that was automatically generated by MySQL for a row after an insert statement has been executed?

PHP PDO lastInsertId() method with examples in MySQL. MySQL has an AUTO_INCREMENT column attribute which automatically generates a consistent integer value upon a successful (or not) INSERT . Oftentimes, this attribute is set on a column deemed the PRIMARY KEY .

What is the purpose of last inserted ID?

Getting MySQL last insert ID is a useful function that lets you quickly and easily retrieve the ID of the last record you added to your database.

How do I find the number of rows in PDO?

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of matching rows.


1 Answers

You've got a few choices:

SELECT @@IDENTITY - return the last ID created by actions of the current connection, regardless of table/scope

SELECT SCOPE_IDENTITY() - last ID produced by the current connection, in scope, regardless of table

SELECT IDENT_CURRENT('name_of_table'); - last ID produced on that table, regardless of table/scope/connection

Of the three, SCOPE_IDENTITY() is the best candidate.

like image 58
Marc B Avatar answered Oct 19 '22 04:10

Marc B