2016-01-01 18 views
0

我有兩個表格,報表和事件,每個表都有一個唯一的標識符,稱爲帶有自動增量的標識,問題是每個表中的標識都不相同,因爲報表可以有事件但可能不是。我想做一個雙插入,但每個表中的一列必須有一個唯一的鍵。我這樣做有以下功能:如何執行以下插入操作mysql

function addactioneventuser(){ 

     try { 

      $this->conn->beginTransaction(); 

       $query = "INSERT INTO 
        " . $this->table_name . " 
       SET 
        case_id = ?, 
        from_to = 0, 
        action_id = ?, 
        accepted = 0, 
        message = ?"; 

     // prepare query statement 
     $stmt = $this->conn->prepare($query); 

     // bind values 
     $stmt->bindParam(1, $this->case_id); 
     $stmt->bindParam(2, $this->action_id); 
     $stmt->bindParam(3, $this->message); 



     // execute the query 
     $stmt->execute(); 

    // insert event query 
     $query2 = "INSERT INTO event_case 

       SET 
        title = ?, body = ?, class = ?, start = ?, end = ?, case_id= ?, worker_id = ?"; 

     // prepare query statement 
     $stmt = $this->conn->prepare($query2); 

     // bind values 
     $stmt->bindParam(1, $this->title); 
     $stmt->bindParam(2, $this->body); 
     $stmt->bindParam(3, $this->class_event); 
     $stmt->bindParam(4, $this->start); 
     $stmt->bindParam(5, $this->end); 
     $stmt->bindParam(6, $this->case_id); 
     $stmt->bindParam(7, $this->worker_id); 

    // execute the query 
     $stmt->execute(); 


    $this->conn->commit(); 
    return true; 



} catch (Exception $e) { 
    $stmt->rollBack(); 
    return false; 
} 

} 

兩個刀片完美的作品,但我的問題是,兩個ID爲每個表是不相同的,因此,我不能在同一時間的特定記錄刪除從兩個表中,我不知道該怎麼做。我閱讀了Cascade和其他可能的解決方案,但沒有一個對我的問題來說似乎是合理的。我不介意創建另一列來將它用作這兩個表的參考,但我不知道如何在上述查詢中執行此操作。

預先感謝您

+0

'last_insert_id()'(http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id) –

+0

這是什麼:MySQL或SQL服務器? –

+0

mysql,對不起我錯過點擊標籤 – lostintheriver

回答

1

最後插入id爲$this->conn->insert_id; 你可以在手術後得到它,並使用的標識符。 例如將其添加到所需表

+0

但我如何保存來自query1的最後一個插入並將值傳遞給query2。我不知道如何在交易查詢中保存該值。 – lostintheriver

+0

您可以分爲兩個操作。執行第一個查詢後,您可以在第二個查詢中使用ID –

+0

謝謝!它現在有效 – lostintheriver

相關問題