当我运行此代码时,我得到无法添加或更新子行:外键约束失败。 我需要帮助来解决这个问题。 include_once('的config.php&#39);
- 第一张表 -
CREATE TABLE welfare_funeral(
welfare_id INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255),
Date Date,
Venue VARCHAR(255)
)ENGINE= INNODB;
- 第二张表 -
CREATE TABLE welfare_funeral_payees(
payee_id INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(255),
Amount VARCHAR(255),
welfare_id INT,
INDEX wel_id(welfare_id),
FOREIGN KEY(welfare_id) REFERENCES welfare_funeral(welfare_id)
)ENGINE=INNODB;
- PHP代码 -
if(isset($_POST['record'])){
$payeeName = $_POST['payeeName'];
$amount = $_POST['amount'];
$welfare_id="SELECT MAX('welfare_id') FROM 'welfare_funeral'";
$myd = $pdo->prepare('INSERT INTO welfare_funeral_payes(Name, Amount, welfare_id)VALUES(:upayeeName, :uamount, :uwelfare_id)');
$myd->bindParam(':upayeeName', $payeeName);
$myd->bindParam(':uamount', $amount);
$myd->bindParam(':uwelfare_id', $welfare_id);
if($myd->execute()){
?>
<script>
alert("New Welfare created");
</script>
<?php
}else{
?>
<script>
alert("Couln't not create Welfare");
</script>
<?php
}
}
答案 0 :(得分:0)
您不能将subselect作为参数放在预准备的Statement中。
您必须首先查询id,然后您可以将这些设置为参数,或者将子选择直接写入语句:
$myd = $pdo->prepare('INSERT INTO welfare_funeral_payes(Name, Amount, welfare_id) SELECT :upayeeName,uamount, MAX(welfare_id) FROM welfare_funeral);
$myd->bindParam(':upayeeName', $payeeName);
$myd->bindParam(':uamount', $amount);
$myd->bindParam(':uwelfare_id', $welfare_id);
也可以使用反引号arround列和表名而不是单引号