2014-06-13 182 views
0

我收到一個錯誤,告訴我表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 
+0

'SHOW CREATE TABLE'請 – hjpotter92

回答

0

LAST_INSERT_ID()僅在同一數據庫連接內有效。你在每個班級打電話database::instance()->connect(),我猜你每次都得到一個新的連接,所以它沒有以前的INSERTLAST_INSERT_ID()

funds::create()的最後一個查詢來自sales::create(),這似乎也是一個糟糕的設計。

你應該有sales::create()返回它添加的行的ID,並通過這個作爲參數傳遞給funds::create()

+0

我確實做到了,它的工作!幫助我擺脫了困境,教會了我更好的設計 – bsapaka

相關問題