繁体   English   中英

如何使用 PDO 和 SQL 服务器获取最后插入行的 ID?

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

在其他情况下,我可能会想使用

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

但由于我将插入用户提交的数据,我想继续使用 PDO,它返回一个空数组。

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时间。

//  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
(
)

我很想知道我做了一些愚蠢的事情,而不是遇到可怕的死胡同:)

你有几个选择:

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() 是最好的候选者。

也许您正在返回两个行集。 尝试添加 SET NOCOUNT ON; 消除 INSERT 的行集,或使用 $stmt->nextRowset 如果您的驱动程序支持它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM