Hi Reader's,
Welcome to FindNerd, today we are going to discuss how to use getLastInsertId() in CakePHP in 2.4.1 version?
In CakePHP there are two methods for getting the last inserted id
1-Model::getLastInsertID()
2-Model::getInsertID()
Suppose you want to get last insert id after saving some data in database, you have to use getLastInsertId() method or getInsertID() to find last inserted from database.
Let see how it is used in CakePHP
<?php
$user_id= $this->ModelName->getInsertID();
$user_id= $this->ModelName->getLastInsertID();
?>
In place of ModelName you have to passed your model name.
let take model name is User in which insert following data.
<?php
//define here parameter to insert in model
$data['username'] = $this->data['username'];
$data['first_name'] = $this->data['first_name'];
$data['last_name'] = $this->data['last_name'];
$data['last_name'] = $this->data['email'];
$data['password'] = $this->data['password'];
$data['role_id'] = $this->data['role_id'];
$data['status']=1;
$result['users']= $this->User->save($data);//here data will insert in to User model
?>
So if you want to get last insert id which is last record has been inserted, So for this you have to use below code.
<?php
$user_id= $this->User->getLastInsertId();
?>
Here user is a model name, when you print $user_id then it will return the last insert id which is last inserted data in User modal.
0 Comment(s)