有什么办法可以解决此代码以避免错误:每次重复键“ PRIMARY”的条目“ 1”

时间:2020-01-01 11:01:09

标签: php mysql primary-key

if(isset($_POST['submit']))
{
    if ($firstName&&$lastName&&$email!=""){
    try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql= "UPDATE abonnenter SET id = (id+1)";
    $conn->exec($sql);
    $sql = "INSERT INTO abonnenter (id,firstname,lastname,mail)
    VALUES (id,'$firstName','$lastName', '$email')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "Du blir nå sendt en mail når bloggen oppdateres";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
    }
}

是代码。当我的id为-1而不是+1时,它可以工作,但是在保持代码语义时,将主键id列为负数似乎非常糟糕

1 个答案:

答案 0 :(得分:0)

使id自动递增。并更新您的sql查询,例如

$sql = "INSERT INTO abonnenter (firstname,lastname,mail)
VALUES ('$firstName','$lastName', '$email')";

您的代码也可以使用pdo或预处理语句对SQL注入开放