2016-03-17 30 views
-2

之後獲取PDO lastInsertId()在我的代碼中,我使用methods將數據插入到MySQL數據庫中。該方法然後返回truefalse在調用方法

如果method返回true我想使用lastInsertId()來運行第二種方法。

if($db->insertMethod($data)){ 
    $lastId = $db->lastInsertId(); 
    $db->secondInsertMethod($lastId, $data2) 
} 

db.class.php

public function insertMethod($data) { 
    $db = new DB(); 
    $insert = //Run SQL insert 
    if($insert > 0) { 
     return true; 
    }else{ 
     return false; 
    } 
} 

public function lastInsertId() { 
     return $this->pdo->lastInsertId(); 
} 

在這種情況下$db->lastInsertId();將返回0。一種解決方法是讓insertMethod返回此代替true,但還有其他方法嗎?

回答

0

已編輯!

解決方案是正確的

data2鏈接到數據?

,您還可以:

public function insertMethod($data, $data2) { 
    $db = new DB(); 
    $insert = //Run SQL insert 
    if($insert > 0) { 
     $this->insertMethod(this->lastInsertId(), $data2); 
     return true; 
    } else { 
     return false; 
    } 
} 

,或者如果數據2被鏈接到數據

public function insertMethod($data) { 
    $db = new DB(); 
    $insert = //Run SQL insert 
    if($insert > 0) { 
     $data2 = // get data2 
     $this->insertMethod(this->lastInsertId(), $data2); 
     return true; 
    } else { 
     return false; 
    } 
} 

public function insertMethod($id, $data) { 
    // your code... 
} 

public function insertMethod($data, $id = null) { 
    $db = new DB();   
    if($id == null) 
     // code to insert without id 
    else { 
     $insert = //Run SQL insert 
     if($insert > 0) { 
      $data2 = // get data2 
      $this->insertMethod($data2, this->lastInsertId()); 
     } 
    } 
} 

的解決方案是正確的。讓你看到你認爲誰最適合你的情況。

+0

當使用'return $ this-> lastInsertId();'方法調用時,它非常有意義。所以這個價值正是我想要的,但是它的方式讓它超越了我所追求的方法。 – Andy