php to return id using Scope_identity

1.5k Views Asked by At

Searching other articles I have come to the conclusion I need to use Scope_Identity() to return the value of the primary key that gets generated when I insert a row into my MS SQL table. However what is not so clear for me is exactly the php I need to return that value. Being fairly new, I have gotten away until now by borrowing code from my predecessor to run sql queries, but they have always been situations where I am returning results from an Array using a while loop. Please advise the correct code.

$query = "INSERT INTO mytable (Title,Author)
          VALUES('".sql_safe($Title)."', '"sql_safe($Author)."'); SELECT Scope_Identity() as myid;";

$result = odbc_exec($con1, $query);

until now I have only ever needed to use

while($row = odbc_fetch_array($result)){ }

but what is the correct way of referring to that myid ?

1

There are 1 best solutions below

0
On

I struggled with this for a while and in the end my solution involved going back to mssql_query driver

$query ="        INSERT INTO powerview.DL_documentlist (Title,Liveversion,Author,Location,Locked,LockedbyID)
                VALUES('".sql_safe($Title)."',1.0,'".sql_safe($Author)."','".sql_safe($Location)."','1',".$lockedbyID."); 
                SELECT SCOPE_IDENTITY() as id;
                RETURN;
             ";

    $result = mssql_query($query);      
    $result = mssql_fetch_object($result);

    $DocID = $result->id;