How to know last id

Hi everyone, how do I retrieve the id of the last save model. for example the code like this

$post = new Post();

$post->title = 'blah';

$post->content = 'blah blah';


$post-><img src='' class='bbc_emoticon' alt='???' /> //how do I get the id that I just now created Post ?

Thanks before :)

$id = $post->getPrimaryKey();

ah yes… it works… Thanks frantic! :)

Or even shorter (if ‘id’ is the name of our primary key):




I have a use case where my entry is properly saved to DB by an ajax call

but when trying to get the new id to pass it back to the json Object

strangely neither of these work




has anybody encountered something like this ?

id is a simple and single primary key on the concerned table

Show your code

if( isset($_POST['Actions'])){

            $validate = $this->performAjaxValidation($model);

            if($validate && count($validate)>0){


        		    echo json_encode(array("result"=>false,"errors"=>$validate));



    		         Yii::app()->user->setFlash('message',"Action hasn't been saved<br/>".$cron->getErrors());


    		} else {

    		    $_POST['Actions']['estimatedStart'] = date('Y-m-d H:i:s',strtotime($_POST['Actions']['estimatedStart']));

    			$_POST['Actions']['estimatedEnd'] = date('Y-m-d H:i:s',strtotime($_POST['Actions']['estimatedEnd']));

    			$_POST['Actions']['effectiveStart'] = date('Y-m-d H:i:s',strtotime($_POST['Actions']['effectiveStart']));

    			$_POST['Actions']['effectiveEnd'] = date('Y-m-d H:i:s',strtotime($_POST['Actions']['effectiveEnd']));


    			$model->desc = $_POST['Actions']['desc'];



    			        echo json_encode(array("result"=>true,"id"=>$id));


    			    } else





I’m also noticing another starnge behavior



in my table I have attributes like name and desc

name is perfectly saved

desc must be manuelly set

$model->desc = $_POST['Actions']['desc'];

or it is never

There’s something strange going on between this and the primaryKey ??

any great idea would be welcome :)

I would suggest you to read the Definitive Guide to Yii if you haven’t done so… If you have then re-read it…

After that create the default webapp and create a model and CRUD for it… then study a bit the generated code until you understand how it works…

For the $model->attributes=$_POST[‘Actions’]; check here -

$validate = $this->performAjaxValidation($model); - this is not good if you use the default performAjaxValidation, because that function does not return anything at all

Does your data get saved at all?

As you are not checking if $model->save() fails…


I made it return an error object for Ajax error passing

yes, but only partially

since my validation is done above it allways goes through the save

some data is saved but others I have to set manuelly

very strange

Did you check the link I gave you about declaring parameters safe?

Thanks mdomba, That was it