20

I am using yii2 php framework. I want insert record into database using transaction. How can I get last inserted id using createCommand().

Please check following code,

$db = Yii::$app->db;
$sql = $db->createCommand()->insert('user', [
                             'name' => 'test',
                             'email_address' => 'test@test.com',
                             'phone_number' => '432432424',
                            ])->execute();
gotqn
  • 42,737
  • 46
  • 157
  • 243
Rahul
  • 223
  • 1
  • 2
  • 10

2 Answers2

43
Yii::$app->db->createCommand($sql)->execute();

Then call function getLastInsertID,

 $id = Yii::$app->db->getLastInsertID();
Kuldeep Dangi
  • 4,126
  • 5
  • 33
  • 56
Chandresh M
  • 3,808
  • 1
  • 24
  • 48
  • 7
    Is this safe against race conditions? E.g. user A inserts into `items` and the id of this just inserted row is 5 and before A calls `getLastInsertID()` user B inserts another row. Now A calls said method. Will he get 5 or 6 ? – DBX12 Mar 17 '17 at 19:36
  • 6 Wins the race! – ajitpawarink Jul 31 '22 at 10:10
5

You can do this using:

$lastInsertID = $db->getLastInsertID();
echo $lastInsertID;
J.K.A.
  • 7,272
  • 25
  • 94
  • 163
  • 1
    possible duplicate of [How to detect the last insert ID within a transaction in Yii using DAO?](http://stackoverflow.com/questions/24014286/how-to-detect-the-last-insert-id-within-a-transaction-in-yii-using-dao) – Sadikhasan Feb 09 '15 at 07:01