How to Get Insert Id in Mssql in 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

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);

Last Inserted id in MSSQL PHP

You have mysql_insert_id, mysqli_insert_id and $mysqli->insert_id for mysql, mysqli procedural and mysqli object style.
All depends on mysql extension you are using

get last inserted id in sql server 2008

I made this function to make it easy :)... if you have more then one db resource just pass that into the mssql_query request. This will retrieve the last unique id generated on that resource connection.

mssql_query("insert into data(name) values('bob')");
$id = getLastId();

function getLastId() {
$result = mssql_fetch_assoc(mssql_query("select @@IDENTITY as id"));
return $result['id'];
}


Related Topics



Leave a reply



Submit