我如何解决违反主键在php(mssql)


how can i solve violation of primary key in php(mssql)?

我有一个三个字段

第一个字段自动编号。(PK)

Second Field是用户id。

最后一个字段是用户pw。

无论如何,这是我的代码。该页面由JSON调用。这个页面可以呼叫多个用户。所以它应该确保冲突id。如果id是冲突的,id应该自动编号到max。
<?php
$conn=mssql_connect('test_database', 'root', '1357');
if (!$conn) {
return -1;
}
header("Content-Type:application/json");
$id=($_POST['id']);
$userid=($_POST['userid']);
$userpw=($_POST['userpw']);
$sql="INSERT INTO dbo.testTable
           (id
           ,userid
           ,userpw)
     VALUES
           ('$id'
           ,'$userid'
           ,'$userpw')";
function customError($errno,$errstr)
{
    if (strpos($errstr,"Violation of PRIMARY KEY")!==false){
        $query_id="
SELECT id
FROM testTable
order by LEN(id) DESC, id DESC
";
        $result_id=mssql_query($query_id,$conn);
        $id=mssql_result($result_id,0,0)+1;
        $result= mssql_query($sql,$conn);
        echo json_encode($result);
    }
    else{
        echo $errstr;
        die();
    }   
}
set_error_handler("customError");
$result= mssql_query($sql,$conn);
echo json_encode($result);
?>

我尝试使用set_error_handler来控制错误消息" Violation of PRIMARY KEY"。

但是$id,$userid,$userpw,$sql不能在set_error_handler函数中使用

Notice: Undefined variable: sql

我建议删除您添加的检查违规部分的函数。然后像这样修改第一个查询,

$sql="INSERT INTO dbo.testTable
       (userid// i have removed the id here
       ,userpw)
 VALUES
       ('$userid'// i have removed $id 
       ,'$userpw')";

或者,如果你想按照你的方法,这样做。

首先替换这一行,因为您将查询存储在$query_id变量中。

$result= mssql_query($sql,$conn);

$result= mssql_query($query_id,$conn);

in customError function.

接下来,不需要将autoincrement id传递给数据库,

$sql="INSERT INTO dbo.testTable
       (id
       ,userid
       ,userpw)
 VALUES
       ('$id'
       ,'$userid'
       ,'$userpw')

我已经删除了第一个参数,因为它在数据库中是自动递增的。