Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last inserted id in yii2 using createCommand? [duplicate]

Tags:

php

mysql

yii2

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();
like image 799
Rahul Avatar asked Feb 09 '15 06:02

Rahul


2 Answers

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

Then call function getLastInsertID,

 $id = Yii::$app->db->getLastInsertID();
like image 150
Chandresh M Avatar answered Sep 22 '22 20:09

Chandresh M


You can do this using:

$lastInsertID = $db->getLastInsertID();
echo $lastInsertID;
like image 22
J.K.A. Avatar answered Sep 22 '22 20:09

J.K.A.