How to get last inserted id in yii2 using createCommand?

36,976

Solution 1

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

Then call function getLastInsertID,

 $id = Yii::$app->db->getLastInsertID();

Solution 2

You can do this using:

$lastInsertID = $db->getLastInsertID();
echo $lastInsertID;
Share:
36,976
Rahul
Author by

Rahul

Updated on July 29, 2022

Comments

  • Rahul
    Rahul almost 2 years

    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' => '[email protected]',
                                 'phone_number' => '432432424',
                                ])->execute();