在数据库中插入数据的问题

时间:2014-10-14 21:05:21

标签: php mysql insert parent-child auto-increment

我做了一个数据库食谱,它由;食谱的名称,身份证号码,成分,准备,图像等。之后我制作了一个php和html脚本,这样我就可以在数据库中搜索(例如:晚餐时间不到45分钟)。不,我正在使用php脚本来插入新的食谱。我可以插入$ sql1。但是有sql2和sql4的问题。问题在于ID auto_increment($ IDGerecht)。并与子/父关系(sql2和sql4)。 目前我收到错误:

Could not enter data retval 2: Cannot add or update a child row: a foreign key constraint fails (`recepten`.`benodigdheid`, CONSTRAINT `benodigdheid_ibfk_1` FOREIGN KEY (`ID`) REFERENCES `gerecht` (`ID`))

创建脚本:

    CREATE TABLE Gerecht 
(ID      INT(3)   AUTO_INCREMENT     NOT NULL,
 gerechtnaam     VARCHAR(35)    NOT NULL,
 personen  NUMERIC(2)    NOT NULL,
 categorie  VARCHAR(25)  NOT NULL,
 bereidingstijd  NUMERIC(3)     NOT NULL,
 bereidingswijze   TEXT   NOT NULL,
 plaatje      VARCHAR(250)      NOT NULL,
 PRIMARY KEY (ID)
);

CREATE TABLE Benodigdheid
(IDbenodigdheid    INT(3) AUTO_INCREMENT   NOT NULL,
 ID    INT(3)     NOT NULL,
 benodigdheden     VARCHAR(35)   NOT NULL,
 PRIMARY KEY (IDbenodigdheid, benodigdheden), 
 FOREIGN KEY (ID) REFERENCES Gerecht (ID)
);

CREATE TABLE Eenheid
(eenheidnaam     VARCHAR(12)    NOT NULL,
 PRIMARY KEY (eenheidnaam)
);

CREATE TABLE Product
(ingredientnaam     VARCHAR(35)    NOT NULL,
 eenheidnaam     VARCHAR(12),
 PRIMARY KEY (ingredientnaam),
 FOREIGN KEY (eenheidnaam) REFERENCES Eenheid (eenheidnaam)
);

CREATE TABLE Ingredient
(IDingredient    INT(3)  AUTO_INCREMENT  NOT NULL,
 ID    INT(3)       NOT NULL,
 ingredientnaam     VARCHAR(35)    NOT NULL, 
 hoeveelheid      NUMERIC(4)    NOT NULL,
 PRIMARY KEY (IDingredient, ingredientnaam),
 FOREIGN KEY (ID) REFERENCES Gerecht (ID),
 FOREIGN KEY (ingredientnaam) REFERENCES Product (ingredientnaam)
);

php代码插入数据:

$sql1="INSERT INTO Gerecht ( gerechtnaam, personen, categorie, bereidingstijd, bereidingswijze, plaatje)
VALUES ('$gerechtnaam','$personen','$categorie','$bereidingstijd','$bereidingswijze','$plaatje')";
$IDGerecht=mysql_insert_id();

$sql2="INSERT INTO Benodigdheid (ID, benodigdheden)
VALUES ($IDGerecht, '$benodigdheden')";
$sql3="INSERT INTO Product (ingredientnaam, eenheidnaam)
VALUES ('$ingredientnaam1', '$eenheid1')";
$sql4="INSERT INTO Ingredient (ID, ingredientnaam, hoeveelheid)
VALUES ($IDGerecht,'$ingredientnaam1', '$hoeveelheid1')";


$retval1 = mysqli_query($db, $sql1 );
if(! $retval1 )
{
  die('Could not enter data retval 1: ' . mysqli_error($db));
}
echo "Entered data retval1 successfully\n</br>";

$retval2 = mysqli_query($db, $sql2 );
if(! $retval2 )
{
  die('Could not enter data retval 2: ' . mysqli_error($db));
}
echo "Entered data retval2 successfully\n</br>";

$retval3 = mysqli_query($db, $sql3 );
if(! $retval3 )
{
  die('Could not enter data retval 3: ' . mysqli_error($db));
}
echo "Entered data retval3 successfully\n</br>";

$retval4 = mysqli_query($db, $sql4 );
if(! $retval4 )
{
  die('Could not enter data retval 4: ' . mysqli_error($db));
}
echo "Entered data retval4 successfully\n</br>";

0 个答案:

没有答案