使用Scope_Identity()的正确方式/位置



我的一个字段中有一个名为deviceID的自动递增ID。我想把它传递给php中的一个会话,以便稍后使用,并计划使用scope_identity(),因为我知道这是获取当前主键ID的最佳方式。然而,每当我尝试使用它时,我都会收到一条错误消息,说它是一个未定义的函数。这是我的代码,所以没有scope_identity():

<?php
session_start();
include 'db.php';
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["screenWidth"] = $screenWidth;
$_SESSION["screenHeight"] = $screenHeight;
if (isset($_POST['submit'])) { 
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$phoneType = $_POST['phoneName'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["HandUsed"] = $HandUsed;
$_SESSION["phoneName"] = $phoneType;
echo 'hello';
$sql = "
INSERT INTO DeviceInfo (DeviceID, screenWidth, phoneType, screenHeight, HandUsed)
VALUES ('$screenWidth','$phoneType', '$screenHeight', '$HandUsed')
SELECT SCOPE_IDENTITY() as DeviceID
";
if (sqlsrv_query($conn, $sql)) {
echo ($sql);
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
}
?>

您需要修复代码中的一些问题:

  • INSERT语句是错误的-您有五列,但该语句中只有四个值。我假设DeviceID是一个标识列,所以从列列表中删除该列
  • 在语句中使用参数。函数sqlsrv_query()同时执行语句准备和语句执行,可用于执行参数化查询
  • 使用SET NOCOUNT ON作为语句的第一行,以防止SQL Server将受影响的行数作为结果集的一部分进行传递
  • SCOPE_IDENTITY()被正确使用,并且它应该返回期望的ID。当然,根据需要,您可以使用IDENT_CURRENT()

以下示例(基于问题中的代码(是一个有效的解决方案:

<?php
session_start();
include 'db.php';
if (isset($_POST['submit'])) { 
$screenWidth = $_POST['screenWidth'];
$phoneType = $_POST['phoneName'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$params = array($screenWidth, $phoneType, $screenHeight, $HandUsed);
$sql = "
SET NOCOUNT ON
INSERT INTO DeviceInfo (screenWidth, phoneType, screenHeight, HandUsed)
VALUES (?, ?, ?, ?)
SELECT SCOPE_IDENTITY() AS DeviceID
";
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo "Error: " . $sql . ": " . print_r(sqlsrv_errors());
exit;
}
echo "New record has been added successfully !";
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row["DeviceID"];
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}
?>

相关内容

  • 没有找到相关文章

最新更新