How to Get Yii last inserted ID from database

Today, We want to share with you Get Yii last inserted ID.
In this post we will show you Yii get last insert id in controller, hear for Yii get last record id we will give you demo and example for implement.In this post, we will learn about how to get id from database in Yii with an example.

Yii last inserted ID – PHP Yii Framework

Get Yii last inserted ID: If We are working with PHP Based Yii MVC models(from database tables) and run The insert/add operation in Database. We can return the last Yii Functions used to inserted id as below.

Syntax for Yii Get Last Inserted Id

Yii Get Last Inserted Id

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

Yii get last insert id in Models

PHP Yii Get Last Inserted Id Using Models

if($model->save())
{
    $LastInsertedId = $model->id 
   // this will be get the last inserted id in Yii
}

Get Yii last inserted ID using PDO

$lastInsertedId = Yii::app()->db->getLastInsertId();
yiiframework

This will return the Yii functions last inserted id in the PHP Yii from Database table.

How to get last inserted record ID in YII2?

In Yii2, you can get the ID of the last inserted record by using the getPrimaryKey() method of the active record object. The following code demonstrates how to insert a new record and retrieve its ID:

$model = new YourModel();
$model->attribute1 = 'value1';
$model->attribute2 = 'value2';

if ($model->save()) {
    $lastInsertedId = $model->getPrimaryKey();
}

Alternatively, you can use the lastInsertID property of the Yii::$app->db component to get the last inserted ID in a database-agnostic way. This property returns the value generated for an AUTO_INCREMENT column by the previous INSERT statement:

$model = new YourModel();
$model->attribute1 = 'value1';
$model->attribute2 = 'value2';

if ($model->save()) {
    $lastInsertedId = Yii::$app->db->lastInsertID;
}

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Yii Get Last Inserted Id.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment