无法添加或更新子行:外键约束失败

Cannot add or update a child row: a foreign key constraint fails

所以我已经为此苦苦挣扎了几天,用谷歌搜索了又用谷歌搜索并四处移动都无济于事:/.

场景如下:一家公司可以有很多产品。

当我尝试为它创建一个新公司和目录时,它创建了目录但没有添加产品并将公司添加到公司 table。

最重要的是我得到这个错误:

Cannot add or update a child row: a foreign key constraint fails (Swifft.Master_Catalog_Testiandoq2, CONSTRAINT Master_Catalog_Testiandoq2_ibfk_1 FOREIGN KEY (Company_ID) REFERENCES Companies (Company_ID) ON DELETE CASCADE ON UPDATE CASCADE)

这是我拥有的:

<?php  include'../Maestro.php';
    //pull all the values from the form.
    $CompName  = mysqli_real_escape_string($conn, $_POST['CompName']);
    $CompName  = ucwords($CompName); //capitalize the first letter of every word

    $ProdSKU   = mysqli_real_escape_string($conn, $_POST['ProdSku']);
    $ProdName  = mysqli_real_escape_string($conn, $_POST['ProdName']);
    $ProdPrice = mysqli_real_escape_string($conn, $_POST['ProdPrice']);
    $ProdDesc  = mysqli_real_escape_string($conn, $_POST['ProdDesc']);
    $ProdStat  = mysqli_real_escape_string($conn, $_POST['ProdStat']);

    echo $CompName . '. . ';
    $CompName  = str_replace(' ', '_', $CompName); // replace spaces with underscores

所以这篇文章就在这里,它创建 table 没有问题。 但是我想我弄错了外键。

    //create a new Master Catalog table for the new company if it doesn't already exist.
    $sql2 = "CREATE TABLE IF NOT EXISTS Master_Catalog_{$CompName} (
    _ID INT(11) AUTO_INCREMENT NOT NULL,
    Company_ID INT(11) NOT NULL,
    Product_Sku VARCHAR(30) NOT NULL,
    Product_Name VARCHAR(100) NOT NULL,
    Product_Price DECIMAL(4,2) NOT NULL,
    Product_Description MEDIUMTEXT NOT NULL,
    Product_Status TINYINT(1) NOT NULL,
    Product_DateAdded DATE NOT NULL,
    Product_DateRemoved DATE,
    PRIMARY KEY(_ID),
    FOREIGN KEY (Company_ID) REFERENCES Companies(Company_ID) ON DELETE CASCADE ON UPDATE CASCADE)";

然后由于某种原因产品没有添加到目录中。

    //add products to the Master Catalog table
    $sql3 = "INSERT INTO Master_Catalog_{$CompName} (
    Product_Sku,
    Product_Name,
    Product_Price,
    Product_Description,
    Product_Status,
    Product_DateAdded)

    VALUES (
    '$ProdSKU',
    '$ProdName',
    '$ProdPrice',
    '$ProdDesc',
    '$ProdStat',
    CURDATE()
    )";

    //check if company exists
    $checkTable = "SELECT * FROM Companies WHERE Company_Name = '{$CompName}' ";
    $result = $conn->query($checkTable);

    //if company does not exists the add it.
    if (mysqli_num_rows($result) == 0){
            echo "there is no row named ". $CompName . ", Im gonna add it.<br/>";
            $sql  = "INSERT INTO Companies (Company_Name, Date_Added) VALUES ('{$CompName}', CURDATE() )";
            $conn -> query($sql) . mysqli_error($conn);
            echo "Complete!";
    }else {
            echo "there is a row named " . $CompName;
    }

    if($conn -> query($sql2) == TRUE){
            echo' Master catalog table created.';
    }else {
            echo " table exists. ";
            echo 'it na work :/'. mysqli_error($conn);}

    if($conn -> query($sql3) == TRUE){
            echo' products added to Master catalog';
    }else {echo 'something exploded! :O'. mysqli_error($conn);}

?>

您需要更改执行顺序,因为在您可以插入 Master_Catalog_{$CompName} table 之前,公司必须存在于 Companies table 中,因为你的外键约束。同样,您不允许在 Company_ID 上使用空值,这意味着您还需要将其包含在插入语句中。

//check if company exists
$checkTable = "SELECT * FROM Companies WHERE Company_Name = '{$CompName}' ";
$result = $conn->query($checkTable);

//if company does not exists the add it.
if (mysqli_num_rows($result) == 0){
        echo "there is no row named ". $CompName . ", Im gonna add it.<br/>";
        $sql  = "INSERT INTO Companies (Company_Name, Date_Added) VALUES ('{$CompName}', CURDATE() )";
        $conn -> query($sql) . mysqli_error($conn);
        echo "Complete!";
        $CompanyId = $conn->last_insert_id;
}else {
        echo "there is a row named " . $CompName;
}

//add products to the Master Catalog table
$sql3 = "INSERT INTO Master_Catalog_{$CompName} (
Company_ID,
Product_Sku,
Product_Name,
Product_Price,
Product_Description,
Product_Status,
Product_DateAdded)

VALUES (
$CompanyId,
'$ProdSKU',
'$ProdName',
'$ProdPrice',
'$ProdDesc',
'$ProdStat',
CURDATE()
)";