密钥' PRIMARY'重复输入在mysql代码中

时间:2017-10-17 10:49:11

标签: php mysql sql

每当我想在数据库中插入内容时,我就会一直收到此错误 我看了一下堆栈,但答案很复杂。

错误是: 订单错误: 重复输入' 936791155'关键' PRIMARY'

$orderID = rand();
$orderQuery = "INSERT INTO Orders (OrderID, PersonID, ProductID, Quantity, Price, 
OrderDate)
VALUES(".$orderID.",".$customerID.",".$productID.",".$selectedQuantity.",".$totalPrice.",'".$today."'";

if(mysqli_query($conn, $sqlQuery)) 
{
    echo "Order has been Successfull!";
} else {
    echo "Order Error: ".$sql. "<br>" . mysqli_error($conn);
}

这是我为MYSQL设置的代码:

CREATE TABLE IF NOT EXISTS Orders (
OrderID int(11) AUTO_INCREMENT, -- Connects to table 'Customer' and ID
PersonID int(11) NOT NULL,  -- Connects to table 'Orders' and OrderUserID
ProductID int(11) NOT NULL,
Quantity int(11) NOT NULL,
Price int(11) NOT NULL,
OrderDate DATETIME,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Customers(PersonID),
FOREIGN KEY (ProductID) REFERENCES Products(ProductID)
);
编辑。我认为这是$ customerID的问题

$customerID = rand();
$sqlQuery = "INSERT INTO Customers (PersonID, FirstName, Address, Phone)
VALUES (".$customerID.",'".$userName."','".$address."','".$phone."')";
    if(mysqli_query($conn, $sqlQuery)) {
     echo "Member verified, in database";
} else{
    echo "Member Error: " . $sql . "<br>" . mysqli_error($conn);
}

2 个答案:

答案 0 :(得分:2)

OrderID是一个自动增量列,您不必在insert语句中设置其值,而是使用此instert:

$orderQuery = "INSERT INTO Orders (PersonID, ProductID, Quantity, Price, 
OrderDate)
VALUES(".$customerID.",".$productID.",".$selectedQuantity.",".$totalPrice.",'".$today."')";

从插入中删除".$orderID.",

我还建议您使用sql参数将值传递给查询,并且不要使用字符串连接。

答案 1 :(得分:0)

我知道有一个答案,但是让我告诉你如何使用预准备语句,这使你的SQL更加安全。

$stmt = $conn -> prepare("INSERT INTO Orders (PersonID, ProductID, Quantity, Price, OrderDate) VALUES (?,?,?,?,?)");
$stmt -> bind_param("iiiss", $customerID, $productID, $selectedQuantity, $totalPrice, $today);

if($stmt -> execute()){
    echo "Order has been Successfull!";
}else {
    echo "Order Error: ".$sql. "<br>" . mysqli_error($conn);
}