2011-12-05 241 views
2

爲什麼?lastInsertId()返回空字符串

try{ 

    $st = $this->prepare("INSERT INTO thetable (a,b) VALUES (?,?)"); 
    $st->execute(array(5,5)); 

    $id = $this->lastInsertId(); 

    echo $id;   // nothing 
    echo gettype($id); // string 

    return $id;   // and I get NULL returned, this is even weirder... 

}catch(PDOException $e){ 
    die($e); 
    return false; 
} 

該表具有自動遞增的id列。爲什麼我不能獲得id值?

+0

發佈lastInsertId函數。 –

+0

http://php.net/manual/en/pdo.lastinsertid.php – Alex

+0

這些值實際上是否被插入? – konsolenfreddy

回答

1

代替

$this->lastInsertId(); 

你試過

$st->lastInsertId(); 
+1

'lastInsertId()'是PDO對象的方法,而不是PDOStatement – Nonym

+1

我真的很想知道這個答案是如何工作的! –

+0

這真的有用嗎? –

5

OK,只是找到了原因。我張貼這是一個答案,因爲最有可能會有其他人誰將會在同樣的問題上運行:d

所以PDO::lastInsertId();將是空的是你怎麼稱呼它PDO::commit()後,我做到了,因爲我是用原子事務。它需要在執行後調用()...

請注意,我沒有的BeginTransaction並在代碼提交()的上方,在我的問題的代碼實際上是正確的,問題是家庭:)

+0

哇,謝謝,這會讓我瘋狂幾天0_0 – Frank

+0

這是沒有在你的問題中指定:) –

+0

是的,抱歉..我不認爲這是相關的發佈確切的代碼 – Alex