V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
cevincheung

分享 PGSQL & PHP 的一个坑

  •  
  •   cevincheung · Jan 21, 2015 · 3360 views
    This topic created in 4115 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
        1
    20150517  
       Jan 21, 2015 via Android
    没commit?
    cevincheung
        2
    cevincheung  
    OP
       Jan 21, 2015
    @20150517 跟那个没关系……就是pg在获取lastinsertid的时候一定要指定seq完整名称。
    a591826944
        3
    a591826944  
       Jan 21, 2015
    @20150517 没有 commit 自增 ID 也会被占用的
    cevincheung
        4
    cevincheung  
    OP
       Jan 21, 2015
    @a591826944 +10086
    joyqi
        5
    joyqi  
       Jan 21, 2015
    这不算一个坑吧,在手册里清楚的写了

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