I am attempting to run a query on an MSSQL database and return the insert ID using PHP. Previously, I had been using the following code for this, which worked fine:
$q = "INSERT INTO Pricing (Products_idProducts,FromQty,ToQty,Price) VALUES((?),(?),(?),(?)); SELECT IDENT_CURRENT('Pricing') AS 'id';";
$params = array( $_POST['idProduct'], $_POST['Pricing-FromQty'], $_POST['Pricing-ToQty'], $_POST['Pricing-Price'] );
$r = sqlsrv_query( $db, $q, $params );
sqlsrv_next_result( $r );
sqlsrv_fetch( $r );
$LastID = sqlsrv_get_field( $r, 0 );
However, due to integration requirements, we added a trigger to the Pricing table that copies the data to a temporary table in another database whenever an INSERT query is run. This kind of changes the order of operations. From what I can tell, the following is occurring:
Web App -> INSERT into Pricing Table
Trigger -> INSERT into Temp Table
Web App -> Get ID
I had previously been using SCOPE_IDENTITY, so it made sense that the trigger was overwriting the last insert ID. But when I figured this out, I switched to IDENT_CURRENT('Pricing') to be more explicit in my request. However, it is still returning a null value.
I should add that if we disable the trigger, this code works perfectly.
Is there any way to return the last inserted ID on a table that has triggers on it?
Thanks so much for any advice or ideas.
EDIT: Here is the Trigger:
IF EXISTS (SELECT 1 FROM inserted cp)
BEGIN
INSERT INTO [ProductManager].._PRICESTAGING ([ITEMNUM],[QFR],[QTO],[PRICE])
SELECT PartNumber,[FromQty],[ToQty],Price
FROM inserted cp
END
EDIT: Solved!
Well, I still don't understand exactly why, but the problem seems to have been caused by a weird combination of both using a trigger, and trying to combine the queries together. Apparently, if a table has a trigger on it, you need to run queries separately. Here is what eventually worked:
$q = "INSERT INTO Pricing (Products_idProducts,FromQty,ToQty,Price) VALUES((?),(?),(?),(?));";
$params = array( $_POST['idProduct'], $_POST['Pricing-FromQty'], $_POST['Pricing-ToQty'], $_POST['Pricing-Price'] );
$r = sqlsrv_query( $db, $q, $params );
// bypass trigger nonsense
$q = "SELECT IDENT_CURRENT('Pricing') AS 'id';";
$r = sqlsrv_query( $db, $q );
$LastID = sqlsrv_fetch_array( $r );
$LastID = $LastID['id'];