2011-12-05 165 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