Kal*_*sin 9 php sql-server pdo sql-server-2000
在其他情况下,我可能会被诱惑使用
$result = mssql_query("INSERT INTO table (fields) VALUES (data);
SELECT CAST(scope_identity() AS int)");
Run Code Online (Sandbox Code Playgroud)
但由于我将插入用户提交的数据,我想继续使用PDO,它返回一个空数组.
不幸的是,我在Linux服务器上运行PHP并使用dblib与不支持的Microsoft SQL Server连接PDO::lastInsertID().
请帮忙!
更新以包含代码示例
这是我正在使用的代码:col1是一个类型的字段,int identitycol2是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 );
Run Code Online (Sandbox Code Playgroud)
这就是显示的内容:
Using MSSQL...
Query OK. Returned ID is 149
Using PDO...
Array
(
)
Run Code Online (Sandbox Code Playgroud)
我很想知道我做了一些愚蠢的事情,而不是遇到一个可怕的死胡同:)
Mar*_*c B 10
你有几个选择:
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
Run Code Online (Sandbox Code Playgroud)
在这三个中,SCOPE_IDENTITY()是最佳候选者.