How to get ID of last inserted record

How can I get ID of last inserted record/row from database table through YII model class object.

Thanks in advance

If your model is called Model, and has a property called id (aka, the PK of the table), then you can acces this way:


$model = new Model();

// do your stuff....


$the_id = $model->id;


Simple, but effective

After a model is inserted into db, it’s “id” property is automatically updated, so you can easily get it: $model->id (or $this->id from inside the model class).

You can also get the last insert id from the corresponding CDbConnection’s property:

It is not showing last inserted ID of database table.

Following is model:

class WaTabMod extends CActiveRecord {

    public static function model($className = __CLASS__){

            return parent::model($className);


    public function tableName(){

        return 'watable';


    public function attributeLabels(){

        return array(

                'id'         => 'Id',

                'wausername' => 'Wa Username',

                'wapassword' => 'Wa Password',

                'waemail'    => 'Wa Email'




Following is ‘create’ method of Controller class:

 public function actionCreate(){

        $model = new WaTabMod;



            echo '<pre>';                


            echo '</pre>';


        $this->render('form', array('model' => $model));


And following is schema :


-- Table structure for table `watable`




  `wausername` varchar(128) NOT NULL,

  `wapassword` varchar(128) NOT NULL,

  `waemail` varchar(128) NOT NULL,

  PRIMARY KEY (`id`)


Can some one guide me why Iam unable to get value of "id" of last inserted record.

Thanks in advance

You have to use $model->save() in order to insert the record in the DB and get the id

What should I do, if my ‘id’ column is not set as AUTOINCREMENT and I have to set its value manually on each new record insertion.

Can I use for this purpose. If so,then can some one guide me how to use it.

Thanks in advance

lastInsertID works only for autoincrement fields… and only if you use it after insert or update…

If you don’t have an autoincrement field than you should give the next value to the field…

one way would be in a transaction first to "select max(field)" so to get the max value of that field and give the returned value+1 to the new record, then save the new record

second way would be to have a table counter where you would keep the nex value… so again in a transaction read the counter value… assign to new record, save new record, increment counter value and save to counter table…

Thanks for reply. What I got from your reply is ----- I have to make a general purpose function which will return maxid of the table. I have concept as follows :

public function myMaxID($tableName, $pkColumnName){

   // Sql statement to get max id of a table 

   return maxId;


Now Iam seeking guidance that where I should place this code so that it should be available in all models and controllers.

Thanks in advance

I think you should create a base class and declare your models to inherit from it

class ActiveRecord extends CActiveRecord 


  public static function model($className=__CLASS__)


    return parent::model($className);




You can make your suggested function a public member of the base class, but since tableName and tableSchema->primaryKey are available as members I would consider to extend or overload save().

(not tested)



Very important thing is (nobody and no manual mentioned it) to unset the ID attribute from $model->attributes like this:


$record = new MyModel;

$record->attributes = $_POST["dataFromForm"];



$myNewId = $record->my_id_column;

This must be done if ‘my_id_column’ was in the form that was just confirmed and that you want to save now. If you do not unset this attribute, Yii has empty string in it, considers it to be a known value and does not refresh it after saving. The value must be NULL when saving.

Neither $model->id

Nor $model->primaryKey

Nor Yii::app()->db->getLastInsertId();

is working

Although data is saving


I have the same problem on one model/table. On most models it works but not on every.

It seems to be some bug in ActiveRecord implementation, because when i did var_dump there wasn’t ID field on dumped data.

my workaround is:

        public function afterSave()



            $this->ID_FIELD = Yii::app()->db->getLastInsertID(SEQUENCE_NAME);


I use sequence name because i work with postgresql, maybe on mysql it’s not necessary

Hey guys!

I’m having a problem very similar to yours… What I want to do is to get de Max ID of a table so I can create a folder named as the last ID I just got…

Any ideas?

Hi Guys,

Today I run in the same issue. My fault was that my primary key was an empty string.

But the primary key will only overwritten when its NULL (===). See CActiveRecord::insert (line 1082).

So when you insert a new Model, add before validate() and save() just:

if(empty($model->id)){ $model->id = NULL; } //id is my primary key

after save/insert you get the key with $model->id. This might happen when you populate the model from a form.

Hope i could help some googlers :)