Get last insert id

Hello, I am using cakePHP 1.3 and I cannot restore the last inserted row id. I really use $ this-> Model-> id to restore the last inserted id, but I cannot get the id. When you tried to check what the return type is, it says like bool (false), which means nothing is returned.

Here I load another model into another controller, so will this be a problem? But even if I download, I get nothing !!

$this->loadModel('Contact'); $this->Contact->query("insert into contacts(tblContact_firstName,tblContact_lastName,tblContact_company,tblContact_department,tblContact_address,tblContact_country,tblContact_city,tblContact_state,tblContact_zipcode,tblContact_phone1,tblContact_email1) values('$sanitizedFormData[fname]','$sanitizedFormData[lname]','','$sanitizedFormData[company]','$sanitizedFormData[address]','$sanitizedFormData[country]','$sanitizedFormData[city]','$sanitizedFormData[state]','$sanitizedFormData[zip]','$sanitizedFormData[phone]','$sanitizedFormData[email]');"); $this->loadModel('Contact'); $contactId = $this->Contact->id; 

And when I printed the $ this-> Contact array recursively, I found that the id value is empty. Therefore, this explains why I was getting an empty value.

Now, given my situation, how do I get the last inserted identifier specific to contacting the controller?

+4
source share
4 answers

When you use query() , you lose a lot of automatic cakephp. Use save() instead.

In fact, you donโ€™t even need to download Contact in this case. You can execute any query from the current controller with query() even when saving to any other table.

You can also avoid using loadModel() if your current model is somehow related to the contact ( $this->CurrentModel->AnotherOne->Contact->save(...) ).

+4
source

If it is MySQl, you can use the query "SELECT from LAST_INSERT_ID ()" to get the last identifier. or just "SELECT LAST_INSERT_ID ()"

For MSSQL, this is "SELECT @@ IDENTITY".

This excludes any solution in cakePHP, so there might be a better solution.

+4
source

You can get the last inserted record id on

 echo $this->ModelName->getLastInsertID(); 

Alternatively you can use:

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

These methods can be found in the file cake / libs / model / model.php on line 2775

Note. This function does not work if you run the insert request manually

+2
source

All Articles