MYSQL和PHP:数据未插入

时间:2017-07-20 05:49:50

标签: php html mysql sql database

我试图将数据添加到这两个外键字段中,但它导致错误。问题是,当我继续使用MYSQL并尝试插入数据时,它实际上确实有效,但是,当我尝试使用php时,我收到以下错误:

Notice: Undefined variable: CantactId in C:\xamppp\htdocs\MDK\profiles.php on line 14
Error updating database: Cannot add or update a child row: a foreign key constraint fails (`companies`.`company`, CONSTRAINT `company_ck` FOREIGN KEY (`CantactId`) REFERENCES `contacts` (`ContactId`) ON DELETE NO ACTION ON UPDATE CASCADE)

此错误仅存在于我的表的外键字段之间,而不存在于其余字段之间。我究竟做错了什么?这是我的PHP代码;如果您还需要查看其他内容,请告诉我,因为我对如何使用本网站并提问我的问题一无所知。

<?php
include('database1.php');

if(isset($_POST['insert']))
{
    $CompanyCode=$_POST['CompanyCode'];
    $CompanyName = $_POST['CompanyName'];
    $Address = $_POST['Address'];
    $Fax = $_POST['Fax'];
    $Website=$_POST['Website'];
    $Telephone = $_POST['Telephone'];
    $ContactId = $_POST['CantactId'];
    $CountryCode=$_POST['CountryCode'];
     $sql = "INSERT INTO `company`(`CompanyCode`, `CompanyName`, `Address`, `Fax`, `Website`, `Telephone`, `CantactId`, `CountryCode`) VALUES ('$CompanyCode','$CompanyName','$Address','$Fax','$Website','$Telephone','$CantactId','$CountryCode')";
     $query=mysql_query($sql) or die ('Error updating database: '.mysql_error());;
   if($query==TRUE)
   {
    header('Refresh:0; details1.php');
   }
   else
       echo "Sorry";
}

?>
  <form action="" method="post">
   Company Code: <input type="text" name="CompanyCode" ><br><br>
   Company Name: <input type="text" name="CompanyName"><br><br>
   Address: <input type="text" name="Address" ><br><br>
   Fax: <input type="number" name="Fax"  ><br><br>
   Website: <input type="text" name="Website"  ><br><br>
    Telephone: <input type="text" name="Telephone"  ><br><br>
   ContactId: <input type="number" name="CantactId"  ><br><br>
   Country Code: <input type="number" name="CountryCode"><br><br>
    <input type="submit" name="insert" value="Insert">
    </form>

</form>

1 个答案:

答案 0 :(得分:2)

你这里有拼写错误。将$CantactId更改为$ContactId

$sql = "INSERT INTO `company`(`CompanyCode`, `CompanyName`, `Address`, `Fax`, `Website`, `Telephone`, `CantactId`, `CountryCode`) VALUES ('$CompanyCode','$CompanyName','$Address','$Fax','$Website','$Telephone','$ContactId','$CountryCode')";

也不要使用 mysql_ 在PHP 7中弃用并完全删除它。使用 mysqli _ PDO 而不是