cevincheung

分享 PGSQL & PHP 的一个坑

  •  
  •   cevincheung · Jan 21, 2015 · 3814 views
    This topic created in 4326 days ago, the information mentioned may be changed or developed.

    PDO,如下代码是无效的

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

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

    请使用如下方法:

    echo $db->lastInsertId('tableName_pkeyName_seq');
    
    Supplement 1  ·  Feb 25, 2015
    sql:

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

    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
    willwen
    Jan 21, 2015 via iPhone❤️2
    6
    習慣用RETURNING id
    cevincheung
    cevincheung
    OP
    Jan 21, 2015
    7
    @willwen
    这是个非常棒的功能!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   930 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 20:49 · PVG 04:49 · LAX 12:49 · JFK 15:49
    ♥ Do have faith in what you're doing.