8

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.

Nunser
  • 4,512
  • 8
  • 25
  • 37
Jaiprakash Singh
  • 73
  • 1
  • 2
  • 6
  • what frd_menus is? Is it somehow related to menus table? – arilia Dec 20 '13 at 10:04
  • duplicate http://stackoverflow.com/a/11020439/1239506 – Moyed Ansari Dec 23 '13 at 06:14
  • You should [accept my answer](http://stackoverflow.com/a/24187920/3197383) because the most upvoted answer is a wrong solution and may cause bugs in your application. To accept my answer, check the check symbol on the left of my answer. – Rémi Becheras Dec 01 '16 at 14:25

11 Answers11

19

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.

XuDing
  • 1,982
  • 18
  • 27
  • 2
    YES! I dont understand why there are so many people using "Model::query()" instead of regular Model methods such as save, saveAssociated, etc. – Guillermo Mansilla Dec 20 '13 at 20:09
  • 2
    $this->Menu->id contains the id as well, straight after the save, without needing to do another trip to the database. – Ben Hitchcock Dec 20 '13 at 23:31
  • This method shoudn't be use for this use case, please read the CAUTION section of my response: http://stackoverflow.com/a/24187920/3197383 to understand why. – Rémi Becheras Dec 01 '16 at 14:22
12

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:

Community
  • 1
  • 1
Rémi Becheras
  • 14,902
  • 14
  • 51
  • 81
4
$this->Menu->getLastInsertId();

you can get the last insert ID by this

Manish Patel
  • 1,877
  • 1
  • 14
  • 15
  • Hi Manish, Thanks for the answer but is not showing the last insert. It works only save() function. – Jaiprakash Singh Dec 20 '13 at 09:47
  • Then use for find->first() with order: id=>DESC – Manish Patel Dec 20 '13 at 09:57
  • Using Model::find('first') would also not be an acceptable solution - you can never guarantee that someone else hasn't saved a record after yours in the time before you make the find call. Example: Thousands of people using the app at the same time and two people perform the same action in close proximity may result in retrieving the wrong ID; This could be catastrophic depending on the situation – jrace Dec 20 '13 at 12:55
  • This method shoudn't be use for this use case, please read the CAUTION section of my response: http://stackoverflow.com/a/24187920/3197383 to understand why. – Rémi Becheras Dec 01 '16 at 14:22
4

use orderby desc option in cakephp.

$lastCreated = $this->Menu->find('first', array('order' => array('Menu.filedname' =>'desc'))`);
Vivek S
  • 2,010
  • 1
  • 13
  • 15
3

You can try :

$data = array('menuName' => $_REQUEST['menuname'])
$this->Menu->create();
$this->Menu->save($data);
$id = $this->Menu->getLastInsertId();
hg8
  • 1,082
  • 2
  • 15
  • 28
Indrajeet Singh
  • 2,958
  • 25
  • 25
  • This method shoudn't be use for this use case, please read the CAUTION section of my response: http://stackoverflow.com/a/24187920/3197383 to understand why. – Rémi Becheras Dec 01 '16 at 14:22
2
$this->Menu->query("INSERT INTO frd_menus SET menuName= '".$_REQUEST['menuname']."'");
$result = $this->Menu->query("SELECT LAST_INSERT_ID()");
$last_id = $result[0][0];

this should works, but I think it will be better if you create a relationship between menus and frd_menus and use save function

arilia
  • 9,373
  • 2
  • 20
  • 44
  • 1
    One should also note that this an SQL injection vulnerability! Never ever inject user input into queries like that, always use `DboSource::value()` for data inserted into [`Model::query()`](http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query)! `$name = $this->Menu->getDataSource()->value($_REQUEST['menuname']); $this->Menu->query("INSERT INTO frd_menus SET menuName=" . $name);` ps. you are missing a closing parenthese/semicolon. – ndm Dec 20 '13 at 11:10
  • 1
    Downvoted for SQL injection and overall this is just wrong. If that's code from a CakePHP app I wonder why you use Cake at all. – floriank Dec 20 '13 at 16:31
  • WHY? WHY? WHY DO YOU USE PLAIN SQL? Please TELL ME WHY!? Furthermore, "$_REQUEST"? like @burzum said, I don't understand why/how you are using CakePHP. – Guillermo Mansilla Dec 20 '13 at 20:11
  • It's not me, I just copied user code. I don't know wy @Jaiprakash Singh uses plain sql, but maybe he has his reason. – arilia Dec 20 '13 at 20:20
  • So, if you see an user writing horrible code then you wouldn't fix it but make it worse? – Guillermo Mansilla Dec 20 '13 at 22:05
2

Very easy. Just do it.

$this->Menu->save($newMenu);
$menuId = $this->Menu->id;
2

Try this

$this->ModelName->save($this->request->data);
$insertedId = $this->ModelName->id;
Sunil kumar
  • 761
  • 5
  • 15
0

In CakePHP 3.x you can do it like:

$data = $this->model->save($data);
$data->id; // this will give the inserted id
CodeWhisperer
  • 1,143
  • 2
  • 19
  • 39
-1
$this->Menu->id; // For User Model

You can also use Model function but below code will return last inserted id of model with given model name for this example it will return Menu model data

$this->Menu->getLastInsertId();
$this->Menu->getInsertID();
Pang
  • 9,564
  • 146
  • 81
  • 122
Md.Jewel Mia
  • 3,345
  • 3
  • 19
  • 24
-1

Below are the options:

echo $this->Registration->id;

OR

echo $this->Registration->getInsertID();

OR

echo $this->Registration->getLastInsertId();

Here, you can replace Registration with your model name.

Note: This function doesn't work if you run the insert query manually

Thanks

Aditya P Bhatt
  • 21,431
  • 18
  • 85
  • 104