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.
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:
$this->Menu->getLastInsertId();
you can get the last insert ID by this
use orderby desc option in cakephp.
$lastCreated = $this->Menu->find('first', array('order' => array('Menu.filedname' =>'desc'))`);
You can try :
$data = array('menuName' => $_REQUEST['menuname'])
$this->Menu->create();
$this->Menu->save($data);
$id = $this->Menu->getLastInsertId();
$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
Very easy. Just do it.
$this->Menu->save($newMenu);
$menuId = $this->Menu->id;
Try this
$this->ModelName->save($this->request->data);
$insertedId = $this->ModelName->id;
In CakePHP 3.x you can do it like:
$data = $this->model->save($data);
$data->id; // this will give the inserted id
$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();
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