pdo lastInsertId returns zero(0)(pdo lastInsertId 返回零(0))
问题描述
所有查询都成功执行,当我检查 MySQL 行中的表插入成功且没有任何错误,但 lastInsertId()
返回 0.为什么?
All queries execute successfully, when I check table in MySQL row inserted successfully without any error, but lastInsertId()
returns 0. why?
我的代码:
// 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());
}
推荐答案
我们必须使用 PDO_MySQL
With PDO_MySQL we must use
$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')");
但遗憾的是,这样做可以减轻 $DB 返回正确插入 ID 的负担.您必须单独运行它们才能检索插入 ID.这将返回正确的插入 ID:
but sadly, doing so relieves the $DB from returning the correct insert id. You would have to run them separately to be able to retrieve the insert id. This returns the correct insert 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();
这甚至不会运行两个查询:
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();
这篇关于pdo lastInsertId 返回零(0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:pdo lastInsertId 返回零(0)
基础教程推荐
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- HTTP 与 FTP 上传 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01