Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
958 views
in Technique[技术] by (71.8m points)

sql server - Microsoft´s sqlsrv driver for PHP not returning any result when querying "SELECT SCOPE_IDENTITY() AS id"

this query works fine using the php_mssql driver:

INSERT INTO Table(columnName) VALUES ('text');
SELECT SCOPE_IDENTITY() AS id;

Table does have an id column, which is an identity. I would execute that query, and get the last id in the table.

The same code doesn′t work if the query is executed using Microsoft′s php_sqlsrv driver.

I don′t get any error when executing the query (sqlsrv_query function) , but i get the following error when calling sqlsrv_fetch_array: "The active result for the query contains no fields"

I′ve googled a lot, and didn′t find no answer, it was a big surprise for me that no one faced this problem before, it seems like nobody is using this driver, even though is the "official" one since PHP 5.3 release...

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the initial CTP the field indices started at 1. Later they were changed to start at 0.

Try something like this:

// connection to the dbserver

$result = sqlsrv_query("INSERT INTO Table(columnName) VALUES ('text'); SELECT SCOPE_IDENTITY() AS ID");

echo "The last insert_id is".lastId($result);

function lastId($queryID) {
     sqlsrv_next_result($queryID);
     sqlsrv_fetch($queryID);
     return sqlsrv_get_field($queryID, 0);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...