gpt4 book ai didi

php - 如何在 SQL Server 中使用 PDO 获取最后插入的行的 ID?

转载 作者:可可西里 更新时间:2023-10-31 23:11:59 25 4
gpt4 key购买 nike

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

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

但是因为我将插入用户提交的数据,所以我想继续使用 PDO,它返回一个空数组。

不幸的是,我在 Linux 服务器上运行 PHP 并使用 dblib 与不支持 PDO::lastInsertID() 的 Microsoft SQL Server 交互。

请帮忙!

更新以包含代码示例

这是我正在使用的代码:col1 是 int identity 类型的字段,col2 是 datetime,默认值为 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
(
)

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

最佳答案

您有几个选择:

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

关于php - 如何在 SQL Server 中使用 PDO 获取最后插入的行的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6140529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com