如何在SQL Server中使用PDO获得最后插入的行的ID? [英] 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)");
但是当我将插入用户提交的数据时,我想继续使用PDO,它将返回一个空数组.
but as I will be inserting user-submitted data, I want to continue to use PDO, which returns an empty array.
不幸的是,我正在Linux服务器上运行PHP,并使用dblib与不支持PDO::lastInsertID()
的Microsoft SQL Server进行接口.
Unfortunately, I'm running PHP on a Linux server and using dblib to interface with Microsoft SQL Server, which doesn't support PDO::lastInsertID()
.
请帮助!
更新为包含代码示例
这是我正在使用的代码:col1是类型int identity
的字段,而col2是默认值为getdate()
的datetime
.
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 );
这是显示的内容:
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 :)
推荐答案
您有几种选择:
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
在这三者中,SCOPE_IDENTITY()是最佳候选人.
Of the three, SCOPE_IDENTITY() is the best candidate.
这篇关于如何在SQL Server中使用PDO获得最后插入的行的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!