50

If I do getLastInsertId() immediately after a save(), it works, but otherwise it does not. This is demonstrated in my controller:

function designpage() {
    //to create a form Untitled
    $this->Form->saveField('name','Untitled Form');
    echo $this->Form->getLastInsertId(); //here it works
}

function insertformname() {
    echo $this->Form->getLastInsertId(); //this doesnt echo at all
}

Please suggest a way to get the functionality I want.

Tom Wright
  • 11,278
  • 15
  • 74
  • 148
useranon
  • 29,318
  • 31
  • 98
  • 146
  • 1
    If you wanted to use the insert ID in a different method, then you’ll need to store it some place, i.e. a session or as a class property in your controller if part of the same request. – Martin Bean Sep 27 '13 at 08:39

22 Answers22

98

CakePHP has two methods for getting the last inserted id: Model::getLastInsertID() and Model::getInsertID(). Actually these methods are identical so it really doesn't matter which method you use.

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

This methods can be found in cake/libs/model/model.php on line 2768

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
nask0
  • 989
  • 6
  • 3
29

Just use:

$this->Model->id;
Brad Koch
  • 19,267
  • 19
  • 110
  • 137
s razu
  • 291
  • 3
  • 2
22

In Cake, the last insert id is automatically saved in the id property of the model. So if you just inserted a user via the User model, the last insert id could be accessed via $User->id

id - Value of the primary key ID of the record that this model is currently pointing to. Automatically set after database insertions.

Read more about model properties in the CakePHP API Docs: http://api.cakephp.org/2.5/class-AppModel.html

Edit: I just realized that Model::getLastInsertID() is essentially the same thing as Model->id

After looking at your code more closely, it's hard to tell exactly what you're doing with the different functions and where they exist in the grand scheme of things. This may actually be more of a scope issue. Are you trying to access the last insert id in two different requests?

Can you explain the flow of your application and how it relates to your problem?

Meer
  • 1,006
  • 10
  • 15
Mike B
  • 31,886
  • 13
  • 87
  • 111
  • inside my insertformname ,i need to update the formname with the last inserted form Id..... – useranon Jun 12 '09 at 06:22
  • Why does Cake give two ways to access the value? Surely the reason is not actually to sow the seeds of confusion. – Steven Lu May 14 '15 at 18:55
9

this is best way to find out last inserted id.

$this->ModelName->getInsertID();

other way is using

$this->ModelName->find('first',array('order'=>'id DESC')) 
Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Urdesh Kumar
  • 1,120
  • 1
  • 17
  • 23
  • your "other way" won't get the right ID if there are more then one person that use your interface – Tamar Sep 26 '17 at 16:33
9

Try using this code in your model class (perhaps in AppModel):

function get_sql_insert_id() {
   $db =& ConnectionManager::getDataSource($this->useDbConfig);
   return $db->lastInsertId();
}

Caveat emptor: MySql's LAST_INSERT_ID() function only works on tables with an AUTO_INCREMENT field (otherwise it only returns 0). If your primary key does not have the AUTO_INCREMENT attribute, that might be the cause of your problems.

Rick
  • 91
  • 1
  • 2
9

You'll need to do an insert (or update, I believe) in order for getLastInsertId() to return a value. Could you paste more code?

If you're calling that function from another controller function, you might also be able to use $this->Form->id to get the value that you want.

brettkelly
  • 27,655
  • 8
  • 56
  • 72
  • In my homepage if i click designpage it by default will create a form entry ..After tat in my designpage i want to change my formname there i m using the function insertformname to update the name ...For this i need the id of it.... – useranon Jun 11 '09 at 07:17
  • Ack. Supposing that designpage() and insertformname() are two different Actions in a Controller, there will be no lastInsertId in the insertformname() Action since you haven't done any database inserts in this action. Each Action (read: page request) is self-containing, you can't get insertIds from a previous page request. – deceze Jun 23 '09 at 08:42
8

There are several methods to get last inserted primary key id while using save method

$this->loadModel('Model');
$this->Model->save($this->data);

This will return last inserted id of the model current model

$this->Model->getLastInsertId();
$this->Model-> getInsertID();

This will return last inserted id of model with given model name

$this->Model->id;

This will return last inserted id of last loaded model

$this->id;
Moyed Ansari
  • 8,436
  • 2
  • 36
  • 57
6

Try to use this code. try to set it to a variable so you can use it in other functions. :)

$variable = $this->ModelName->getLastInsertId();

in PHP native, try this.

$variable = mysqli_insert_id();
r3mmel
  • 656
  • 4
  • 13
5

This will return last inserted id of last loaded model

$this->id;

This will return last inserted id of model with given model name

$this->Model->id;

This will return last inserted id of the model current model

CakePHP has two methods for getting the last inserted id: Model::getLastInsertID() and Model::getInsertID().

echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();
GIPSSTAR
  • 2,050
  • 1
  • 25
  • 20
5

Below are the options:

echo $this->Registration->id;

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

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

Here, you can replace Registration with your model name.

Thanks

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

Use this one

function designpage() {
//to create a form Untitled
$this->Form->saveField('name','Untitled Form');
echo $this->Form->id; //here it works

}

MuntingInsekto
  • 1,543
  • 4
  • 19
  • 36
  • 1
    I am not sure it was really necessary to warm up an ancient question and repost an answer that has already been given. – mark May 23 '13 at 09:30
3

You can get last inseted id with many ways.Like Model name is User so best way to fetch the last inserted id is

$this->User->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 User model data

$this->User->getLastInsertId();
$this->User->getInsertID();
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
3

When you use save(), the last insert ID is set to the model’s $id property. So:

if ($this->Model->save()) {
    printf('Last insert ID was %s', $this->Model->id);
}
Martin Bean
  • 38,379
  • 25
  • 128
  • 201
3

Each time a save method is called on a model, cake internally calls Model::getLastInsertId() and stores the result into model class attribute id, so after calling save() it is not necessary to call Model::getLastInsertId() or inserId(), as tha value can be directly accessed like this

$id = $this->id;// within a model
$id = $this->{$this->modelName}->id;// in a controller
Sumit Kumar
  • 1,855
  • 19
  • 19
2

After insertion of data, we can use following code to get recently added record's id:

    $last_insert_id=$this->Model->id;
Vineet Kumar
  • 187
  • 2
  • 6
2

each time you perform an insert operation on any model, cake internally fetchesthe last insert Id and Sets to Model->id attribute.

so one can access it directly by $Model->id;, no need to query again for lastInsertId.

Sumit Kumar
  • 1,855
  • 19
  • 19
2

I think it works with getLastInsertId() if you use InnoDB Tables in your MySQL Database. You also can use $this->Model->id

Ammar
  • 51
  • 6
1

This is interesting, I also stumbled upon this issue. What you asked perhaps how to get the last ID of a certain model regardless of it's state, whether it's just been inserted or not. To further understand what getInsertID does, we need to take a look at the source:

Link 1: http://api20.cakephp.org/view_source/model#line-3375

public function getInsertID() {
  return $this->_insertID
}

Yup, that's the only piece of code inside that function. It means that cakephp caches any last inserted ID, instead of retrieve it from the database. That's why you get nothing if you use that function when you haven't done any record creation on the model.

I made a small function to get the last ID of a certain table, but please note that this should not be used as a replacement of getLastID() or getLastInsertID(), since it has an entirely different purpose.

Add the function lastID() to the AppModel as shown below so that it can be used system wide. It has it's limit, which can't be used on model with composite primary key.

class AppModel extends Model {
  public function lastID() {
    $data = $this->find('first', 
      array(
        'order' => array($this->primaryKey . ' DESC'),
        'fields' => array($this->primaryKey)
      )
    );

    return $data[$this->name][$this->primaryKey];
  }
}

Original Source : Class Model

MarmiK
  • 5,639
  • 6
  • 40
  • 49
O.O
  • 7,179
  • 1
  • 34
  • 32
1

Actually you are using the getLastInsertId or getInsertId in a wrong manner. getLastInsertId() is meant to work only after save() method. It will even not work after a manual insert, as cake engine is storing the mysql_insert_id under $this->_insertID inside the save method which can be retrieved via the getLastInsertId or getInsertId. Now in your case

$this->Model->id

OR

$this->Model->find('first',array('order'=>'id DESC')) 

Will do.

1

In CakePHP you can get it by: Model::getInsertID() //Returns the ID of the last record this model inserted. Model::getLastInsertID() //Alias to getInsertID().

Andolasoft Inc
  • 1,296
  • 1
  • 7
  • 16
1
$Machinedispatch = 
   $this->Machinedispatch->find('first',array('order'=>array('Machinedispatch.id DESC')));

Simplest way of finding last inserted row. For me getLastInsertId() this not works.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
0
$this->Model->field('id', null, 'id DESC')
Robert
  • 25
  • 2
  • 4
    This approach is wrong...Eventually it will happen, that you get id of a row inserted between your model creation and this call. Use getLastInsertID(); – Elwhis May 06 '11 at 00:19