简体   繁体   English

pdo lastInsertId 返回零(0)

[英]pdo lastInsertId returns zero(0)

All queries execute successfully, when I check table in MySQL row inserted successfully without any error, but lastInsertId() returns 0 .所有查询都成功执行,当我检查MySQL行中的表插入成功时没有任何错误,但lastInsertId()返回 0 why?为什么?

My code:我的代码:

// 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());
     }

With PDO_MySQL we must use使用 PDO_MySQL 我们必须使用

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

so that we can run multiple queries like:这样我们就可以运行多个查询,例如:

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

but sadly, doing so relieves the $DB from returning the correct insert id.但遗憾的是,这样做可以减轻 $DB 返回正确插入 ID 的负担。 You would have to run them separately to be able to retrieve the insert id.您必须单独运行它们才能检索插入 ID。 This returns the correct insert id:这将返回正确的插入 ID:

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

but this won't:但这不会:

$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();

and this won't even run the two queries:这甚至不会运行两个查询:

$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();

Place $dbh->lastInsertId();放置$dbh->lastInsertId(); Before $dbh->commit() and After $stmt->execute();$dbh->commit()$stmt->execute();

I'm also having same issue This code is always returning 0 我也遇到同样的问题,此代码始终返回0

if($stmt -> execute()){
        $productId = Connection::connector()->lastInsertId();   
        return $productId;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM