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 :)
You've got a few choices:
Of the three, SCOPE_IDENTITY() is the best candidate.
Maybe you are getting two rowsets returned. Try adding SET NOCOUNT ON; to eliminate the INSERT's rowset, or use $stmt->nextRowset if your driver supports it.