getInsertId()

Returns the auto-increment ID of the last successfully inserted row using insert(), insertMulti(), or replace(). Useful when you need to retrieve the primary key right after an insert operation.

Signature:

public function getInsertId(): int|string|null

Basic Example

// Insert a new user
$data = [
  'firstname' => 'Alice',
  'lastname'  => 'Example',
  'email'     => 'alice@example.com'
];

$db->insert('test_users', $data);
$id = $db->getInsertId();  // e.g., 1542
Note: For insertMulti(), only the ID of the first inserted row is returned (if applicable). For insertBulk(), no insert ID is available.

Use Cases

  • Immediately retrieve the ID of a new user, order, or post
  • Reference the ID for follow-up inserts (e.g. inserting related rows)
  • Track inserted entities in application logic or logs

See Also