Reputation: 68072
Why?
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;
}
The table has an id column which has auto increment. Why don't I get the id value?
Upvotes: 2
Views: 1535
Reputation: 68072
ok, just found out why. I'm posting this as an answer because most likely there will be others who will run in the same problem :D
So PDO::lastInsertId();
will be empty is you call it after PDO::commit()
, which I did because I was using atomic transactions. It needs to be called after execute()...
Note that I don't have beginTransaction and commit() in the code above so the code in my question is actually correct, the problem was home :)
Upvotes: 5
Reputation: 459
instead of
$this->lastInsertId();
have you tried
$st->lastInsertId();
Upvotes: 1