Getting Last Insert Id in view file

Hello All,

I want to show the last login id from the database in view > _form.php file.I have made the code in _form.php file like this




  <div class="row">

    <?php echo $form->labelEx($model,'id'); ?>

    <?php echo Yii::app()->db->getLastInsertId();?>

    <?php echo $form->error($model,'id'); ?>

  </div>

  

After this I am getting error like


 ID: 0

.So how to get the getLastInsertId.Any help and suggestions will be highly appriciable.A

Looks like you have to specify the table name:

http://www.yiiframework.com/doc/api/1.1/CDbCommandBuilder#getLastInsertID-detail

That should do it.

Thanks @rookie84 for your reply.According to your suggestion I tried this


<div class="row">

    <?php echo $form->labelEx($model,'id'); ?>

    <?php echo Yii::app()->db->getLastInsertId('Form');?>

    <?php echo $form->error($model,'id'); ?>

  </div>

Here Form is the table and the model name.But Still I am getting


 ID:0

.Where is the wrong part?

Just noticed Yii::app()->db->getLastInsertId() works only after an insert or update transaction and also if you have the primary key auto incremented, in that case $model->id is also available which is the id of the last inserted item.

If you just want to find out the last inserted id (not after an insert or update) you might try something like this (AGAIN, PK SHOULD BE AUTOINCREMENTED)


$lastId = Yii::app()->db->createCommand('SELECT id FROM yourTable ORDER BY id DESC LIMIT 1')->queryScalar();

this will pull out the maximum value off the yourTable.

Hope this solves your problem.


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