参照完整性错误

时间:2015-12-08 20:30:52

标签: php mysql

我在数据库期末考试项目中遇到参考完整性错误时遇到了一些麻烦。我试图弄清楚自己,但无济于事,我希望有人能指出我正确的方向。

问题是我有三个表,前两个表是第三个表的父表。我正在尝试构建一个PHP脚本,它将更新两个父表,然后将数据插入子表。到目前为止,我认为可行,但每当我尝试使用它时,我都会收到以下错误:

  

INSERT INTO Purchases(CustomerID,PurchaseOrderNo,PurchaseTotal,DateOfPurchase,SalesPersonID,SpecialOrder)VALUES('10','0000','100.00','0000-00-00','5555','N')< / p>      

无法添加或更新子行:外键约束失败('xxxxxx'。'购买',CONSTRAINT'Ponsseses_ibfk_1'FOREIGN KEY('CustomerID')REFERENCES'CustomerInfo'('CustomerID')ON DELETE CASCADE ON UPDATE CASCADE)'

我出错的任何想法?

        ########## FOREIGN KEY CHECK START ##########
$sql = "select count(*) as count from CustomerInfo where '$customerid' = CustomerID";
$result = mysqli_query($con,$sql)
or  die('Error: ' . mysql_error());

$row = mysqli_fetch_assoc($result);
    if ( $row['count']==0 ){
    "INSERT INTO CustomerInfo ('CustomerID') VALUES ('$customerid');";
    echo "<p>Customer ID Not Found. <br />New CustomerID Created.</p>";
   }

$sql2 = "select count(*) as count from EmployeeInfo where '$salespersonid' =  SalesPersonID;";
$result2 = mysqli_query($con,$sql)
 or  die('Error: ' . mysql_error());
 $row2 = mysqli_fetch_assoc($result2);

if ( $row2['count']==0 ){
"INSERT INTO EmployeeInfo ('SalesPersonID')VALUES ('$salespersonid');";
echo "<p>Salesperson ID Not Found. <br />New Salesperson ID Created.</p>";
}

    ########## FOREIGN KEY CHECK END ##########

    ########## DATA ENTRY SQL STATEMENT START ##########
$sql3 = "INSERT INTO Purchases (CustomerID, 
          PurchaseOrderNo, 
          PurchaseTotal, 
          DateOfPurchase, 
          SalesPersonID,
          SpecialOrder) 
VALUES ('$customerid',   
        '$purchaseorderno',
        '$purchasetotal',
        '$dateofpurchase',
        '$salespersonid',
        '$specialorder')";
    ########### DATA ENTRY SQL STATEMENT END ##########

    ########## INPUT SUCCESS/FAILURE REPORTING#########
if (mysqli_query($con, $sql3)) {
    echo "<P>Record Successfully Created</P><BR />";
} else {
  echo "Error: " . $sql9. "<br>" . mysqli_error($con);
}
mysqli_close($con);
echo "<P>Connection Successfully Closed.</P>";

1 个答案:

答案 0 :(得分:0)

您没有为 CustomerInfo EmployeeInfo

执行插入查询
    $sql = "select count(*) as count from CustomerInfo where '$customerid' = CustomerID";
    $result = mysqli_query($con,$sql)
    or  die('Error: ' . mysql_error());

    $row = mysqli_fetch_assoc($result);
        if ( $row['count']==0 ){

    ###THE NEXT LINE DOESN'T DO ANYTHING###
        "INSERT INTO CustomerInfo ('CustomerID') VALUES ('$customerid');";
        echo "<p>Customer ID Not Found. <br />New CustomerID Created.</p>";
       }

此外,您不希望在insert语句中的列名称周围放置单引号,而不是:

INSERT INTO CustomerInfo ('CustomerID') VALUES ('$customerid')

你想要:

INSERT INTO CustomerInfo (CustomerID) VALUES ('$customerid')