Retrieve the ID of an inserted record: Php & MS SQL SERVER
http://www.php.net/manual/en/function.mssql-query.php#104263
I don't use MS SQL at all but have briefly read up on this. It would seem you need to make a call to sqlsrv_next_result. An example is provided in that comment:
$query = "INSERT INTO test (col1, col2) VALUES (?,?); SELECT SCOPE_IDENTITY()";
$resource=sqlsrv_query($conn, $query, $arrParams);
sqlsrv_next_result($resource);
sqlsrv_fetch($resource);
echo sqlsrv_get_field($resource, 0);
First, do not use @@identity
for this purpose if you value the integrity of your data as it can return the wrong answer. Even worse, it can work correctly for years before someone puts a trigger on the table and it starts quietly sending the wrong value.
Use the OUTPUT
clause or Scope_identity()
.
Example of the SQL used to do the output clause:
DECLARE @MyTableVar table( myID int,
myName varchar(50),
ModifiedDate datetime);
INSERT dbo.mytable
OUTPUT INSERTED.myID, INSERTED.myName, INSERTED.ModifiedDate
INTO @MyTableVar
VALUES ('test', GETDATE());
This works for me...
$sql = "Insert into MyTable(column1,column2,column3) VALUES (? , ? , ?); SELECT @@IDENTITY as id;";
$params = array($value1,$value2,$value3);
$stmt = sqlsrv_query( $conn, $sql, $params);
$next_result = sqlsrv_next_result($stmt);
$row = sqlsrv_fetch_array($stmt);
echo "ROW INSERTED WITH ID : " . $row["id"];
if( $stmt === false ) {
Echo "Error writing new application to table";
}