<p>I believe you can use <code>getLastInsertID</code> to fetch the ID:</p>

<pre><code>Craft::$app-&gt;db-&gt;getLastInsertID();
</code></pre>

CC BY-SA 4.0
2020-05-12T11:15:28.897Z
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.
Piotr Pogorzelski
CC BY-SA 4.0
2020-05-12T12:01:23.323Z
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
CC BY-SA 4.0
2020-05-12T12:12:07.903Z
Unfortunately i still get `Calling unknown method: craft\db\Command::getLastInsertID()` error.
Piotr Pogorzelski
CC BY-SA 4.0
2020-05-12T12:19:15.607Z
Actually, it worked! But is it possible that it returns wrong value? For example if two db inserts are performed in nearly same time.
Piotr Pogorzelski
CC BY-SA 4.0
2020-05-12T12:21:59.310Z
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
CC BY-SA 4.0
2020-05-12T11:09:43.610Z
2020-05-12T13:29:23.683Z
2020-05-12T13:29:23.683Z
Martin Spain
<p>I insert data into database table using query builder:</p>

<pre><code>$command = Craft::$app-&gt;db-&gt;createCommand()-&gt;insert('test2', array());
$command-&gt;execute();
</code></pre>

<p>How can i retrieve <code>id</code> of newly inserted db row?</p>

<database>
Get id of row inserted into database
# Get id of row inserted into database

(Asked by: username_0 on 2020-05-12)

I insert data into database table using query builder:
$command = Craft::$app->db->createCommand()->insert('test2', array());
$command->execute();

How can i retrieve id of newly inserted db row?

**Tags:** database


---

## 1 answers

### Answer by username_1 on 2020-05-12. Score: 2 | Accepted answer

I believe you can use getLastInsertID to fetch the ID:
Craft::$app->db->getLastInsertID();

> **Comments:**
> **username_0**: 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.  
> **username_1**: Ah, I meant to write `Craft::$app->db->getLastInsertID();`. That'll teach me to cut and paste quickly, my apologies. Give that a try.  
> **username_0**: Unfortunately i still get `Calling unknown method: craft\db\Command::getLastInsertID()` error.  
> **username_0**: Actually, it worked! But is it possible that it returns wrong value? For example if two db inserts are performed in nearly same time.  
> **username_1**: 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.  

---

