简体   繁体   English

从PHP中的MS SQL Server查询返回插入记录的ID

[英]Return ID of inserted record from MS SQL Server Query in PHP

I am trying to return the id result from this query using "OUTPUT INSERTED.ID". 我正在尝试使用“ OUTPUT INSERTED.ID”从此查询返回ID结果。 In my SQL Server Management Studio I get the id of the newly inserted row. 在我的SQL Server Management Studio中,我获得了新插入的行的ID。 I need to return that result. 我需要返回该结果。

I am trying this, I know the connection is working and everything because it is making the insert into the table. 我正在尝试此操作,我知道连接正在运行,并且一切正常,因为它正在将插入表插入。 But $value still returns 0. 但是$ value仍然返回0。

public function Insert($NewSql) {
$value = '0';
$params = array(array($value,SQLSRV_PARAM_OUT));
$stmt = sqlsrv_query($this->conn, $NewSql, $params);
return $value;

}

The parameter NewSql = "Insert Into Test (Col1) OUTPUT INSERTED.ID VALUES ('SomeValues')"; 参数NewSql =“插入测试(Col1)OUTPUT INSERTED.ID VALUES('SomeValues')”“;

For some reason $value is still returning 0. 由于某种原因,$ value仍返回0。

Figured it out. 弄清楚了。

 public function Insert($IncomingSql) {
    //Append the Select for Scope_Identity to IncomingSql
    $sql = $IncomingSql.'; SELECT SCOPE_IDENTITY();';
    $Result = sqlsrv_query($conn,$sql); 
    sqlsrv_next_result($Result); 
    sqlsrv_fetch($Result);

    return sqlsrv_get_field($Result, 0); 

}

Then call it like 然后像这样称呼它

$ID = Insert("Insert Into Table (SomeColumn) Values ('SomeValue)") and $ID will have the last inserted ID.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM