分享 PGSQL & PHP 的一个坑

2015 年 1 月 21 日
 cevincheung

PDO,如下代码是无效的

$db->beginTransaction();
$db->prepare('insert......')
   ->execute();
echo $db->lastInsertId();

你永远也无法获得到lastInsertId的值。

请使用如下方法:

echo $db->lastInsertId('tableName_pkeyName_seq');
3360 次点击
所在节点    PostgreSQL
7 条回复
20150517
2015 年 1 月 21 日
没commit?
cevincheung
2015 年 1 月 21 日
@20150517 跟那个没关系……就是pg在获取lastinsertid的时候一定要指定seq完整名称。
a591826944
2015 年 1 月 21 日
@20150517 没有 commit 自增 ID 也会被占用的
cevincheung
2015 年 1 月 21 日
@a591826944 +10086
joyqi
2015 年 1 月 21 日
这不算一个坑吧,在手册里清楚的写了

Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver. For example, PDO_PGSQL requires you to specify the name of a sequence object for the name parameter.
willwen
2015 年 1 月 21 日
習慣用RETURNING id
cevincheung
2015 年 1 月 21 日
@willwen
这是个非常棒的功能!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://study.congcong.us/t/164196

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX