Get all inserted IDs when inserting multiple rows using a single query

前端 未结 7 1128
误落风尘
误落风尘 2021-01-17 11:40

I\'ve already looked at other answers and I still feel that my question is relevant and deserves a separate entry.

I have a table named settings(which stores user se

7条回答
  •  余生分开走
    2021-01-17 12:10

    This behaviour shouldn't be relied upon; besides the obvious locking issues, let's say you want to set up master<->master replication; all of a sudden, the id's increment by 2 every time.

    Besides that, instead of actually writing multiple insert statements, it might be worth using prepared statements:

    $db = new PDO(...);
    $db->beginTransaction();
    $stmt = $db->prepare('INSERT INTO `mytable` (a, b) VALUES (?, ?)');
    
    foreach ($entries as $entry) {
        $stmt->execute(array($entry['a'], $entry['b']));
        $id = $db->lastInsertId();
    }
    
    $db->commit();
    

提交回复
热议问题