我收到一個錯誤,告訴我表funds
中的列sale_id
的值在表sales
中不存在。該值是通過獲取前一個SQL查詢的LAST_INSERT_ID
得出的。每個查詢都存在於不同類的不同實例中。註釋的代碼如下:MySQL完整性約束違規:1452
//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
'SHOW CREATE TABLE'請 – hjpotter92