Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last id in cakephp

Tags:

cakephp

I am using query in cakephp

$this->Menu->query("INSERT INTO frd_menus SET menuName= '".$_REQUEST['menuname']."'");

How to get last insert id of this query in cakephp? Please advice.

like image 908
Jaiprakash Singh Avatar asked Dec 20 '13 09:12

Jaiprakash Singh


3 Answers

If there is no specific reason.

You should use

$this->Menu->save($data)

to insert the data. Then you can use

$this->Menu->getLastInsertId();

to get the last inserted id.

like image 136
XuDing Avatar answered Oct 31 '22 14:10

XuDing


In almost cases you should use the model method to query your database.

Model::query() exists to run complex queries that will be more complex than using the model methods, or in a few cases when you have not the choice.

In your case this is very useful because Model::save() runs a callback in the framework that set the Model::id attribute for you.

So, this permit you to get it back immediately:

if ($this->Menu->save($data)) {
   $lastId = $this->Menu->id;
}

BE CAUTION !

On the other side and like said by other responses there is the following method:

Model::getLastInsertId()

But YOU MUST BE VERY CAREFUL with this method and YOU SHOULD'NT USE IT IN THIS USE CASE because it get the LAST inserted, but NOT the last you just inserted in the previous code statement!

If a user (during another concurrent request on the server) save data between save() and getLastInsertId(), it will return that of this second user!

THUS, the following answers are BAD answers for this use case:

  • https://stackoverflow.com/a/20701165/3197383
  • https://stackoverflow.com/a/20700561/3197383
  • https://stackoverflow.com/a/24059193/3197383
  • https://stackoverflow.com/a/29874758/3197383
like image 40
Rémi Becheras Avatar answered Oct 31 '22 13:10

Rémi Becheras


$this->Menu->getLastInsertId();

you can get the last insert ID by this

like image 4
Manish Patel Avatar answered Oct 31 '22 13:10

Manish Patel