The driver sqlsrv does not have any native function to recover the id of the inserted record. In this case it is necessary to send two queries at once only the first INSERT
and the second one SELECT
in scope_identity which will return the value of the entered Identity field.
sqlsrv_next_result returns true if there is something(resultsets, number of affected rows or yet another output) in the preprocessed sql statement that is stored in the variable $stmt
. Every call of sqlsrv_next_result()
an sql is popped to get its return use sqlsrv_fetch_*
The code should stay that way:
$sql = "INSERT INTO [RDO].[dbo].[ANALISE_CRITICA]
(CC, NMANALISE, TXTOBS, VLRECEITACONT, VLRECEITABRUTA)
VALUES (?,?,?,?,?); SELECT SCOPE_IDENTITY() AS last_id";
$params = array($cc, $analiseCritica, $objetoExtra,
$receitaContrato, $receitaBrutaMarco);
$stmt = sqlsrv_query($conn, $sql, $params); //processa a consulta
$next_result = sqlsrv_next_result($stmt); //em caso sucesso desempilha a proxima sql(select)
if($next_result){
$item = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); //obtem o resultado
echo $item['last_id'];
}
Note: avoid using @
in the code they mask the error messages and make it difficult to detect the problem, handle the error.
Based on:
Soen
manual - sqlsrv_next_result
http://www.criaweb.com/artigos/181.php ;]
– MarceloBoni
Do you already know how to connect to the database and execute queries in SQL Server with PHP? That is, you are only searching the query, or all the way?
– bfavaretto
Specify the driver you are using. If you are mssql or the sqlsrv
– rray
Yes, it is connected to the bank. I am using sqlsrv.
– GustavoSevero
Despite the votes to close for this reason, I think the question is clear. What is missing is more details of the current implementation.
– Caffé