V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
cevincheung
V2EX  ›  PostgreSQL

分享 PGSQL & PHP 的一个坑

  •  
  •   cevincheung · 2015-01-21 16:40:39 +08:00 · 2768 次点击
    这是一个创建于 3397 天前的主题,其中的信息可能已经有所发展或是发生改变。

    PDO,如下代码是无效的

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

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

    请使用如下方法:

    echo $db->lastInsertId('tableName_pkeyName_seq');
    
    第 1 条附言  ·  2015-02-25 17:27:50 +08:00
    sql:

    insert into tabel ( field ) values (val) returning primary_key
    7 条回复    2015-01-21 17:31:38 +08:00
    20150517
        1
    20150517  
       2015-01-21 16:45:29 +08:00 via Android
    没commit?
    cevincheung
        2
    cevincheung  
    OP
       2015-01-21 16:53:47 +08:00
    @20150517 跟那个没关系……就是pg在获取lastinsertid的时候一定要指定seq完整名称。
    a591826944
        3
    a591826944  
       2015-01-21 16:56:53 +08:00
    @20150517 没有 commit 自增 ID 也会被占用的
    cevincheung
        4
    cevincheung  
    OP
       2015-01-21 16:57:22 +08:00
    @a591826944 +10086
    joyqi
        5
    joyqi  
       2015-01-21 17:00:11 +08:00
    这不算一个坑吧,在手册里清楚的写了

    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
        6
    willwen  
       2015-01-21 17:24:00 +08:00 via iPhone   ❤️ 2
    習慣用RETURNING id
    cevincheung
        7
    cevincheung  
    OP
       2015-01-21 17:31:38 +08:00
    @willwen
    这是个非常棒的功能!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1015 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 19:48 · PVG 03:48 · LAX 12:48 · JFK 15:48
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.