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.
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.
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()
andgetLastInsertId()
, 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
$this->Menu->getLastInsertId();
you can get the last insert ID by this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With