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);
Getting the id of the last inserted record from an MSSQL table using PDO and PHP
If your id
column is named id
you can use OUTPUT
for returning the last inserted id
value and do something like this:
$CustID = "a123";
$Name="James"
$stmt = "INSERT INTO OrderHeader (CustID, Name)
OUTPUT INSERTED.id
VALUES (:CustID, :Name)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result["id"]; //This is the last inserted id returned by the insert query
Read more at:
https://msdn.microsoft.com/en-us/library/ms177564.aspx
http://php.net/manual/es/pdo.lastinsertid.php
How to get Insert id in MSSQL in PHP?
@@IDENTITY
returns the most recent identity generated in the current session. In most cases you'll probably want to use SCOPE_IDENTITY
instead, which returns the most recent identity generated in the current scope.
For example, if you insert a row into table1, but that insert fires a trigger which inserts a row into table2, then @@IDENTITY
will return the identity from table2 whereas SCOPE_IDENTITY
will return the identity from table1.
INSERT INTO my_table (my_column) VALUES ('test')
-- return the identity of the row you just inserted into my_table
-- regardless of any other inserts made by triggers etc
SELECT SCOPE_IDENTITY() AS ins_id
Last inserted value on SQL Server with PHP
$query = "INSERT INTO [dbo].[Participante] ([nome],[email],[telefone],[unidadeCE],[dataCadastro]) VALUES ('" . $nome . "', '" . $email . "', '" . $telefone . "', '" . $unidade . "', (getdate())); SELECT SCOPE_IDENTITY()";
$resource=sqlsrv_query($conn, $query, $arrParams);
sqlsrv_next_result($resource);
sqlsrv_fetch($resource);
echo sqlsrv_get_field($resource, 0);
Reference:
Related Topics
Pre-Incrementation VS. Post-Incrementation
Get Facebook Meta Tags with PHP
Cakephp Does Not Use My Models
Check If the Query Results Empty Row MySQLi
PHP Keep Checkbox Checked After Submitting Form
Parametrized Pdo Query and 'Limit' Clause - Not Working
Reordering Checkout Fields in Woocommerce 3
Html,PHP - Escape '<' and '>' Symbols While Echoing
How to Access a Deep Object Property Named as a Variable (Dot Notation) in PHP
Is There a Good PHP Geolocation Service
PHP Simplexml Namespace Problem
Parse Error: Invalid Numeric Literal
Warning: MySQL_Query(): 3 Is Not a Valid MySQL-Link Resource