pdo lastInsertId返回零(0)

时间:2013-12-31 14:35:11

标签: php mysql pdo lastinsertid

当我检查 MySQL 行中的表格成功插入而没有任何错误时,所有查询都成功执行,但lastInsertId() 返回0 。为什么呢?

我的代码:

// queries executes successfully, but lastInsetId() returns 0
// the menus table has `id` column with primary auto_increment index
// why lastInsertId return 0 and doesn't return actual id?


$insertMenuQuery = " 
 SELECT @rght:=`rght`+2,@lft:=`rght`+1 FROM `menus` ORDER BY `rght` DESC limit 1; 
 INSERT INTO `menus`(`parent_id`, `title`, `options`, `lang`, `lft`, `rght`) 
      values 
  (:parent_id, :title, :options, :lang, @lft, @rght);";
     try {
           // menu sql query
           $dbSmt = $db->prepare($insertMenuQuery);

           // execute sql query
           $dbSmt->execute($arrayOfParameterOfMenu);
           // menu id
           $menuId = $db->lastInsertId();

           // return
           return $menuId;

     } catch (Exception $e) {
          throw new ForbiddenException('Database error.' . $e->getMessage());
     }

2 个答案:

答案 0 :(得分:7)

使用PDO_MySQL我们必须使用

$DB->setAttribute(PDO::ATTR_EMULATE_PREPARES,TRUE); // there are other ways to set attributes. this is one

这样我们就可以运行多个查询,如:

$foo = $DB->prepare("SELECT * FROM var_lst;INSERT INTO var_lst (value) VALUES ('durjdn')");

但遗憾的是,这样做可以减轻$ DB返回正确的插入ID。您必须单独运行它们才能检索插入ID。这将返回正确的插入ID:

$DB->setAttribute(PDO::ATTR_EMULATE_PREPARES,TRUE);
$foo = $DB->prepare("INSERT INTO var_lst (value) VALUES ('durjdn')");
$foo->execute();
echo $DB->lastInsertId();

但这不会:

$DB->setAttribute(PDO::ATTR_EMULATE_PREPARES,TRUE);
$foo = $DB->prepare("SELECT * FROM var_lst;INSERT INTO var_lst (value) VALUES ('durjdn')");
$foo->execute();
echo $DB->lastInsertId();

这甚至不会运行两个查询:

$DB->setAttribute(PDO::ATTR_EMULATE_PREPARES,FALSE); // When false, prepare() returns an error
$foo = $DB->prepare("SELECT * FROM var_lst;INSERT INTO var_lst (value) VALUES ('durjdn')");
$foo->execute();
echo $DB->lastInsertId();

答案 1 :(得分:4)

$dbh->lastInsertId();之前和之后$dbh->commit()

放置$stmt->execute();