【发布时间】:2019-11-25 16:30:49
【问题描述】:
所有查询都成功执行,当我检查 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());
}
【问题讨论】:
-
这读起来很混乱....你能删除行号并重新格式化代码吗?
-
执行多个查询时看nextRowSet() stackoverflow.com/a/11271707/46675
-
MSSQL 不提供 lastInsertId() php.net/manual/en/pdo.lastinsertid.php的解决方法
-
如果你单独执行它们会发生什么?
-
他们执行成功
标签: php mysql pdo lastinsertid