I insert data into database table using query builder:

$command = Craft::$app->db->createCommand()->insert('test2', array());

How can i retrieve id of newly inserted db row?


I believe you can use getLastInsertID to fetch the ID:

| improve this answer | |
  • This causes Calling unknown method: craft\db\Command::getLastInsertID() error. I searched craft docs for this function and it is in craft\db\pgsql - i use mysql. – piotrpog May 12 at 11:15
  • Ah, I meant to write Craft::$app->db->getLastInsertID();. That'll teach me to cut and paste quickly, my apologies. Give that a try. – Martin Spain May 12 at 12:01
  • Unfortunately i still get Calling unknown method: craft\db\Command::getLastInsertID() error. – piotrpog May 12 at 12:12
  • Actually, it worked! But is it possible that it returns wrong value? For example if two db inserts are performed in nearly same time. – piotrpog May 12 at 12:19
  • I've wondered about that too. Honestly, I don't know, but I think that PHP's single-threaded nature would mean it's very unlikely (if not impossible) that another insert could happen between the two lines of your code. – Martin Spain May 12 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.