Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting last inserted value in Yii

Tags:

php

mysql

yii

I have already made a model for form.In that the fields were like

id
firstname
lastname
description
created_at
updated_at
created_by
updated_by

I have made necessary CRUD for Form.Now I want to get one extra field for last inserted id in view file.So how to get that value?To get that value should I make any necessary changes in CRUD?Any help and suggestions will be highly appriciable.

like image 354
NewUser Avatar asked Feb 25 '12 11:02

NewUser


5 Answers

You can get the last inserted ID like this:

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

See the Yii documentation for more information.

like image 165
fivedigit Avatar answered Oct 16 '22 09:10

fivedigit


If your goal is to get the id that was assigned to the model that you just saved, then after you do $model->save(), simply do $model->id to get it back.

like image 38
Aaron Avatar answered Oct 16 '22 09:10

Aaron


If $model->id wouldn't work then use Yii::app()->db->getLastInsertId() or getPrimaryKey().

like image 41
Kaletha Avatar answered Oct 16 '22 09:10

Kaletha


you can also get the last inserted id of another model.

$std_id = Students::model()->findAll(array('order' => 'admission_no DESC','limit' => 1));

            foreach($std_id as $f) {

                echo  "Last Inserted Admission No:".$f['admission_no'];
                }

or

you can last inserted id in the same model

Yii::app()->db->getLastInsertID();
like image 2
Elango Mani Avatar answered Oct 16 '22 09:10

Elango Mani


In Yii2 last inserted id can be get using

Yii::$app->db->getLastInsertedID();

added for the people looking for the answer of same question in yii2

like image 2
Kuldeep Dangi Avatar answered Oct 16 '22 10:10

Kuldeep Dangi