dongpu3898 2015-10-26 04:06 采纳率: 100%
浏览 15

我怎样才能解决php(mssql)中主键的违规问题?

I have a three field.

First Field is auto numbering.(PK)

Second Field is user id.

Last Field is user pw.

Anyway, This is my code. This page called by JSON. This page can call multiple user. so it should ensure conflict id. if id is conflict, id should be auto numbering to 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);
?>

I Try control error message 'Violation of PRIMARY KEY" by using set_error_handler.

But $id,$userid,$userpw,$sql can not use in set_error_handler function.

Notice: Undefined variable: sql
  • 写回答

1条回答 默认 最新

  • douan8473 2015-10-26 04:18
    关注

    I would suggest to remove that function which you have added to check that violation part. and change your first query like this,

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

    Or if you want to follow your method, do like this.

    First replace this line, because you are storing the query in $query_id variable.

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

    to

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

    in customError function.

    Next, no need to pass autoincrement id to your database,

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

    I have removed first parameter since its an autoincrement in database.

    This should solve both errors.

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀