How to get last inserted id from sqlsrv_execute() with prepared statement for multiple inserts?

Viewed 298

I'm pretty new at PHP, but I'm trying to address it. Let's say I have an insert prepared statement (sqlsrv_prepare()), that I would re-use multiple times by just replacing variable values, then re-executing it.

The foo table uses IDENTITY(1,1).

My statement is:

insert into foo (bar, baz) 
values (?, ?); 

Select SCOPE_IDENTITY() as LAST_ID;

My parameter array is composed by array( &$bar, &$baz). This way, For a thousand inserts, I could just replace $bar and $baz values and re-run the statement.

But here is the question: Since sqlsrv_execute() returns a bool value, how could I retrieve the last "statement-inserted" Id to push it onto an array?

I know that I could just use sqlsrv_query() to do that... I don't know, but I think it would be slower (since sqlsrv_query() prepares and executes a query, so I think, internally it would run a "prepare function" every time it runs) than executing the same statement multiple times by just replacing parameter values.

I know how to get last inserted id, which row was inserted using sqlsrv_query() from here, and here.

How could I accomplish that for sqlsrv_execute()? Am I doing it wrong way?

Thank you in advance!

0 Answers
Related