Php MySQL完整性约束冲突:1452
我收到一个错误,告诉我表Php MySQL完整性约束冲突:1452,php,mysql,Php,Mysql,我收到一个错误,告诉我表基金中列sale\u id的值在表sales中不存在。此值是通过获取上一个sql查询的LAST\u INSERT\u ID得到的。每个查询都存在于不同类的不同实例中。注释代码如下: //this method which runs the first query belongs to this class class sales { public $sale_id, $acc_id, $sale_amt,
基金中列sale\u id
的值在表sales
中不存在。此值是通过获取上一个sql查询的LAST\u INSERT\u ID
得到的。每个查询都存在于不同类的不同实例中。注释代码如下:
//this method which runs the first query belongs to this class
class sales {
public $sale_id,
$acc_id,
$sale_amt,
$sale_date;
public function create() {
$db = database::instance()->connect();
$sql = "INSERT INTO sales (sale_id,acc_id,sale_amt,sale_date) VALUES (DEFAULT, :acc_id, :sale_amt, :sale_date)";
$query = $db->prepare($sql);
$query->execute(array(
':acc_id' => $this->acc_id,
':sale_amt' => $this->sale_amt,
':sale_date' => $this->sale_date)
);
$perc = (Get('accounts','acc_perc','acc_id',$this->acc_id)); $perc = $perc[0];
//create an instance of another class, "funds"
$fund = new funds;
$fund->acc_id = $this->acc_id;
$fund->fund_amt_total = $perc * $this->sale_amt;
$fund->fund_date = $this->sale_date;
//call a method of the class "funds"
$fund->create();
}
}
第二个类,运行第二个查询
class funds {
public $fund_id,
$acc_id,
$sale_id,
$fund_amt,
$fund_date;
public function create() {
$db = database::instance()->connect();
//sale_id is the value returned from LAST_INSERT_ID(), which is the sale_id from the preceding entry
$sql = "INSERT INTO funds (sale_id,fund_id,acc_id,fund_amt,fund_date) VALUES (LAST_INSERT_ID(),DEFAULT,:acc_id,fund_amt,:fund_date)";
$query = $db->prepare($sql);
$query->execute(array(
':acc_id' => $this->acc_id,
':fund_amt' => $this->fund_amt_total,
':fund_date' => $this->fund_date)
); //error occurs on this line
}
}
第一个错误代码:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`coop1`.`funds`, CONSTRAINT `funds_ibfk_2` FOREIGN KEY (`sale_id`) REFERENCES `sales` (`sale_id`))' in C:\wamp\www\coop1\1\classes.php on line 62
第二个错误代码
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`coop1`.`funds`, CONSTRAINT `funds_ibfk_2` FOREIGN KEY (`sale_id`) REFERENCES `sales` (`sale_id`)) in C:\wamp\www\coop1\1\classes.php on line 62
LAST\u INSERT\u ID()
仅在同一数据库连接中有效。在每个类中调用database::instance()->connect()
,我猜每次都会得到一个新的连接,因此它没有上一个INSERT
中的最后一个插入ID()
让funds::create()
依赖于上一个查询来自sales::create()
这一事实似乎也是一个糟糕的设计
您应该让sales::create()
返回它添加的行的ID,并将其作为参数传递给funds::create()
SHOW create TABLE
请我正是这样做的,它成功了!帮助我克服困难,教我更好的设计