我在尝试获取最后插入行的主键(VisitID)时遇到问题。
每当运行查询时,DB都会更新,但sqlsrv_get_field永远不会返回VisitID。我应该使用 sqlsrv_query 而不是 sqlsrv_prepare 还是有些东西我完全失踪?
$addvisitquery = "
INSERT INTO blah;
SELECT SCOPE_IDENTITY() AS VisitID";
$addVisit = sqlsrv_prepare($connect,$addvisitquery);
if( sqlsrv_execute($addVisit))
{
echo "Statement executed.\n <br />";
echo "Number of rows updated:".sqlsrv_rows_affected($addVisit)." <br />";
sqlsrv_next_result($addVisit)." <br />";
sqlsrv_fetch($addVisit);
echo "Returned VisitID:".sqlsrv_get_field($addVisit, 0)." <br />";
sqlsrv_commit($connect);
答案 0 :(得分:0)
很简单,确保您的SQL语句具有以下内容以返回最后插入的行:
; SELECT SCOPE_IDENTITY()
创建一个php函数:
function lastInsertId($queryID) {
sqlsrv_next_result($queryID);
sqlsrv_fetch($queryID);
return sqlsrv_get_field($queryID, 0);
}
然后添加此行以查询函数:
echo "The last inserted row ID is ".lastInsertId($addVisit);